简体   繁体   中英

Removing all subviews from a UITableViewCell except imageView

I am creating a custom cell and I add subviews to it for text mostly. At first the subviews were not getting deleted when the cell was reused, so the text would overwrite and blot really bad. Then I added this for loop to the function and it solved my problem except that it also completely removes my imageView and it never gets re-added, so my whole tableview is missing the image that is supposed to be associated with each cell.

The if statement didn't work, but I didn't explicitly use cell.addSubView() as i did for the cell labels, so I am wondering if that has something to do with it. I have googled and found that most people are saying this worked for them, but I just cannot seem to figure it out.

Why does this remove my images, why won't they come pack like the other subviews, and how can I fix this?

I have the following code:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
    for subView in cell.subviews {  
        if subView as? NSObject != cell.imageView {
            subView.removeFromSuperview()
        }
    }
    var statusImage = UIImage(named:imageConfigration(indexPath.row))!
    cell.imageView?.image = statusImage
    // ...
}

Give your imageView a tag in storyboard or xib or programmatically what you are using. Now in the for loop of subviews check if tag of the subview is equal to tag to imageview dont remove it.

Also another option to solve this if it fits your requirement is to hide all the elements added to cell except imageview. That will be much faster then looping in subviews and removing it you never know what all subview are attached to cell other then you added by iOS but thats if it fits your req. Let me know in case of any concern

This how you can do this

cell.textLabel.hidden = YES;

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