我正在尝试制作一个表格,其中第一个单元格的布局与其余单元格不同。我想将图像作为第一个单元格的背景,即它看起来像这样:
这是我的实现代码
func imageCellAtIndexPath(indexPath:NSIndexPath) -> MainTableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier(imageCellIdentifier) as MainTableViewCell
let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject
let eTitle:NSString = object.valueForKey("title")!.description
let deTitle = eTitle.stringByDecodingHTMLEntities()
cell.artTitle.text = deTitle
var full_url = object.valueForKey("thumbnailURL")!.description
var url = NSURL(string: full_url)
var image: UIImage?
var request: NSURLRequest = NSURLRequest(URL: url!)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
image = UIImage(data: data)
if((indexPath.row)==0) {
var imageView = UIImageView(frame: CGRectMake(10, 10, cell.frame.width - 10, cell.frame.height - 10))
imageView.image = image
cell.backgroundView = UIView()
cell.backgroundView?.addSubview(imageView)
}
else{
cell.thumb.image = image
}
})
return cell
}
问题是……当我向下滚动并再次向上滚动时,背景图像开始重复,缩略图也重叠,如下所示:
如果我再次上下滚动……会发生以下情况:
我可能犯了一些愚蠢的错误,但我无法弄清楚它是什么。请帮忙
最佳答案
在表格 View 中,单元格被重复使用,并且您应该重置单元格的部分,这些部分与您所追求的单元格样式的特定版本无关。像这样的东西:
if((indexPath.row)==0) {
let frame = CGRectMake(10, 10,
cell.frame.width - 10, cell.frame.height - 10)
var imageView = UIImageView(frame: frame)
imageView.image = image
cell.backgroundView = UIView()
cell.backgroundView?.addSubview(imageView)
// Reset
cell.thumb.image = nil
} else{
cell.thumb.image = image
// Reset
cell.backgroundView = nil
}
更好和更惯用的想法是为这两种单元格类型使用单独的 UITableViewCell
设计,每种都有不同的重用标识符。这样你就不需要关心重置了。
附言您应该使用 dequeueReusableCellWithIdentifier:forIndexPath:
而不是旧的 dequeueReusableCellWithIdentifier:
因为它保证返回一个单元格。
关于ios - swift indexPath.row==0 对 UITableViewCell 的工作很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28579209/