Odd behavior with UITableView in Swift

耗尽温柔 提交于 2019-12-02 15:44:55

问题


I have a custom cell with two labels and a image. I receive some data from internet in Json. Everything works fine; every cell fills with the correspondent data. I've added a new label that has to be filled just like the other ones. This is the data:

let cell = tableView.dequeueReusableCellWithIdentifier("friendCell") as! friendCell

cell.friendPicture?.image = newImageUser

cell.friendName.text = "@\(theName[indexPath.row])"

if repliesNumber[indexPath.row] == "0"{

        cell.repliesNumber.textColor = UIColor.redColor()
    }
    else{

        cell.repliesNumber.textColor = UIColor(patternImage: UIImage(named:"backgroundPattern")!)
    }

if AttachedImage[indexPath.row] != ""{

        cell.backgroundColor = .orangeColor()

    }

For testing I've made to be colored the first two cells. My issue is that the fist two cells get colored, but if I scroll down, every two, three, four cells (depending on the device -device height I guess-, another two cells get colored too.

It's odd/weird because the rest of labels work fine.

Where should I start looking?

If I print the json data I receive everything is okay

Here is a gif:

GIF

Basically my problem is that when I scroll down the data disappear but only from a label, the rest of labels and images doesn't.


回答1:


It's not very clear from your code which are the cells that are "colored". Is it from the orangeColor() condition ?

Anyway, UITableViewCells in an UITableView are reused, which means you are given them in the exact same state you left them. This is why, if you don't reset your backgroundColor, they still are orange as you scroll.

So basically, whenever you do something in a certain condition in a cell, don't forget to restore its state when the condition is not met. In your case, this gives :

// cellForRowAtIndexPath {
if itemIsMultimedia() {
    cell.Multimedia.text = "it's multimedia"
    cell.Multimedia.hidden = false
}
else {
    cell.Multimedia.text = ""
    cell.Multimedia.hidden = true
}



回答2:


here @aimak

if AttachedImage[indexPath.row] != ""{

        cell.Multimedia.text = "It's multimedia"

    }
    else{

        cell.Multimedia.hidden = true
    }


来源:https://stackoverflow.com/questions/34707234/odd-behavior-with-uitableview-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!