我有一个自定义 UITableViewCell
,它显示带有缩略图的视频。我正在以编程方式添加缩略图 UIImageView
。但是,当我的 UITableView
中有超过 1 行时,单元格的 UIImageView
会显示在所有其他单元格中。例如,如果我有 2 个单元格,UIImageView
在单元格 1 中显示正常,但单元格 2 UIImageView
在单元格 3 中显示。抱歉,如果这令人困惑。如果需要更多信息,请告诉我。
这是我在 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
}
}
最佳答案
在 getDataInBackgroundWithBlock
完成下载 imageData
时,单元格对象可能已经被不同的 indexPath 重用。
当您使用 dequeueReusableCellWithIdentifier
和 cell.contentView.addSubview()
时,您将添加太多 subview 。
所以你可以试试下面的代码。
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)
//......
}
关于ios - 以编程方式将 UIImageView 添加到 UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34584071/