[英]Adding an UIImageView to a UITableViewCell programmatically
我有一个自定义UITableViewCell
,它显示带有缩略图的视频。 我正在以编程方式添加缩略图UIImageView
。 但是,当我的UITableView
有多于一行时,单元格的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
}
}
如果您不太了解tableview单元的重用,建议您在委托方法中设置与indexPath绑定的UI元素的hidden属性。
像这样添加代码
if (clipObjects![indexPath.row].objectForKey("thumbnail")) {
thumbnail.hidden = false
} else {
thumbnail.hidden = true
}
在getDataInBackgroundWithBlock
完成下载imageData
的时间时,单元格对象可能已被其他indexPath重用。 在使用dequeueReusableCellWithIdentifier
和cell.contentView.addSubview()
,您将添加过多的子视图。 因此,您可以尝试以下代码。
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)
//......
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.