简体   繁体   中英

Adding an UIImageView to a UITableViewCell programmatically

I have a custom UITableViewCell that shows videos with their thumbnail images. I'm adding the thumbnail UIImageView programmatically. However, when I have more than 1 row in my UITableView , the cells' UIImageView shows in every other cell. For example, if I have 2 cells, the UIImageView appears fine in cell 1, but the cell 2 UIImageView shows in cell 3. Sorry if that is confusing. Let me know if there's more information needed.

Here is the code I use in cellForIndexPath :

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCellWithIdentifier("videoCell")! as! VideoCell
    cell.selectionStyle = UITableViewCellSelectionStyle.None // get rid of highlight when tapping a cell

    if videoCollections.count > 0 {
        let singleVideoCollection = videoCollections[indexPath.row]
        // get video clips from PFRelation
        let clips = singleVideoCollection.relationForKey("clips")
        let query = clips.query()

        query.findObjectsInBackgroundWithBlock { (clipObjects, error) -> Void in

            if error == nil {

                for (index, clip) in (clipObjects?.enumerate())! {
                    if index == 0 { // first clip

                        let firstThumbnailImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 54, height: 54))
                        firstThumbnailImageView.center = cell.center
                        firstThumbnailImageView.layer.cornerRadius = firstThumbnailImageView.frame.height / 2
                        firstThumbnailImageView.clipsToBounds = true
                        let thumbnail = clip.objectForKey("thumbnail")
                        thumbnail!.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in
                            if (error == nil) {
                                firstThumbnailImageView.image = UIImage(data:imageData!)
                                cell.contentView.addSubview(firstThumbnailImageView)
                            }
                        }

                    }
                }
            }
        }

        return cell

    }
}

This is the outcome when I have 2 cells. Notice how the second UIImageView is in a third cell: 在此处输入图片说明

If you do not understand the reusing of the tableview cell well, it is recommended that you set the hidden property of the UI elements binding with the indexPath in the delegate method.

add code like this

if (clipObjects![indexPath.row].objectForKey("thumbnail")) {
    thumbnail.hidden = false
} else {
    thumbnail.hidden = true
}

At the time getDataInBackgroundWithBlock finishes downloading the imageData , cell object might already have been reused for a different indexPath. And as you are use dequeueReusableCellWithIdentifier and cell.contentView.addSubview() ,you will add too much subviews. So you can try the follow code.

class VideoCell: UITableViewCell {
//......
let firstThumbnailImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 54, height: 54))

override func prepareForReuse() {
  super.prepareForReuse()
  firstThumbnailImageView.image=nil;
}
//......
}


func tableView(tableView : UITableView, cellForRowAtIndexPath indexPath : NSIndexPath)->UITableViewCell {
//......
// let firstThumbnailImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 54, height: 54))

cell.firstThumbnailImageView.center = cell.center
cell.firstThumbnailImageView.layer.cornerRadius = firstThumbnailImageView.frame.height / 2
cell.firstThumbnailImageView.clipsToBounds = true
let thumbnail = clip.objectForKey("thumbnail")

//......

//cell.contentView.addSubview(firstThumbnailImageView)

//......
}

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