简体   繁体   中英

Image Disappears when i am scrolling UITableView

I'm using UITableView to display my data.

My data consist of an image and text. The problem is when I'm scrolling the UITableView the image disappears.

This is my code:

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return msgs.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! collCell
    let msg = msgs[indexPath.row]
    var decodeImgURL = ""
    cell.lbl1.text = msg.content

    decodeImgURL = msg.imgurl

    if decodeImgURL == "none" {
        cell.img.isHidden = true
    } else {

        let dataDecoded : Data = Data(base64Encoded:decodeImgURL,options: .ignoreUnknownCharacters)!
        let decodedImage = UIImage(data: dataDecoded)
        cell.img.image = decodedImage

    }

    return cell
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    let msg = msgs[indexPath.row]

    if msg.imgurl == "none" {
        return 64
    } else {
        return 207
    }

}

With a UITableView , the only cells that are in memory are the visible cells. When you scroll a table cell off the screen, it is removed from memory. This helps the table view scroll faster. The issue you are facing is that when you scroll the table cell off the screen, the cell (along with the image) are deallocated from memory. When you scroll the cell back onto the screen it is allocated into memory again. I think your issue could be from one of two problems:

1) You just need to wait a few seconds for your image to be re-created in the cell.

2) Perhaps there is an issue in your msgs array. If the image does not appear after a couple seconds, try to put a breakpoint right after this line: cell.img.image = decodedImage . If that breakpoint is not reached after scrolling your cell off the screen then back onto the screen, then the issue is that the decodeImgURL (url of your image) is incorrect.

Strange, because there are no solutions still for Swift5

The simplest option is to update the image each period of time (let's say 1 second)

    Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in

        self.pictureImageView?.image = your_image
    }

Then deallocate the Timer with timer.invalidate() at viewDidDisappear() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM