L
L
Lorem Ipsum2019-12-24 11:23:03
JavaScript
Lorem Ipsum, 2019-12-24 11:23:03

UITableView jumping images received from server?

Hello! I get the url of the image from the server, load the image and put it in the UIImageView, when scrolling, the pictures behave very strangely, they seem to be replaced. What can be wrong? Video for clarity - https://vk.com/video-58860049_456239362

extension UIImageView {
    func load(url: URL) {
        DispatchQueue.global().async { [weak self] in
            if let data = try? Data(contentsOf: url) {
                if let image = UIImage(data: data) {
                    DispatchQueue.main.async {
                        self?.image = image
                    }
                }
            }
        }
    }
}

extension NewsViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return newsArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier) as! NewsTableViewCell
        let newsItem = newsArray[indexPath.row]
        
        cell.titleLabel?.text = newsItem.postTitle
        cell.shortDestLabel?.text = newsItem.postShortDesc
        cell.dateLabel?.text = newsItem.postDate
        
        let imageUrlString = newsItem.postImageUrl!.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        
        cell.coverImageView?.load(url: URL(string: imageUrlString!)!)
        
        return cell
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
alex, 2019-02-19
@lemonlimelike

<body>
  <div><span class="span" data-genres="a, b, c"></span></div>
  <div><span class="span" data-genres="d, e, f"></span></div>
  <div><span class="span" data-genres="g, h, i"></span></div>
  <div><span class="span" data-genres="j, k, l"></span></div>
  
  <script>
    function addGenres(genres, container) {
      genres.split(', ').forEach(genre => {
        const linkNode = document.createElement('a');
        const textNode = document.createTextNode(genre);

        linkNode.setAttribute('href', `/category/${genre}`);
        linkNode.setAttribute('class', 'content__box__genre--links');
        linkNode.appendChild(textNode);

        container.appendChild(linkNode);
      })
    }
  </script>
  <script>
    document.querySelectorAll('.span').forEach(el => {
      addGenres(el.dataset.genres, el)
    })
  </script>
</body>

B
briahas, 2019-12-24
@GeorgeGeorge

The cells are then reused. And the block inside load(url:) is bound to self. coverImageView, which means that when the cell is reused, it will not reset to zero and will continue to execute .... in parallel with another block.
So, you need to delete the old block.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question