[英]How to load content view inside a tableview cell?
I have created a table view as 我已经创建了一个表视图
var tblView : UITableView = UITableView()
tblView.frame = CGRectMake(0, 168, 320-50 , 450)
tblView.separatorColor = UIColor.clearColor()
tblView.scrollEnabled = false
tblView.rowHeight = 39
self.addSubview(tblView)
tblView.delegate = self
tblView.dataSource = self
tblView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "myCell")
Now i am trying to add custom view to the tableviewcell as 现在我试图将自定义视图添加到tableviewcell作为
//MARK: table view data source methods
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("myCell") as UITableViewCell
var cellImgView:UIImageView = UIImageView()
cellImgView.frame = CGRectMake(cell.contentView.frame.origin.x+10, cell.contentView.frame.size.height, 20, 20)
let cellImage = UIImage(named: self.cellImgs[indexPath.row])
cell.backgroundColor = UIColor(red: 0.000, green: 0.400, blue: 0.404, alpha: 1.00)
cellImgView = UIImageView(image: cellImage)
cell.contentView.addSubview(cellImgView)
return cell
}
Only first image is at correct position and other are overlapped.Why is this happening? 为什么只有第一个图像位于正确的位置,其他图像却重叠?
cellForRowAtIndexPath will called each time when cell in user's sight. 每当用户看到单元格时,都会调用cellForRowAtIndexPath。 But you need add UIImageView only once. 但是您只需要添加一次UIImageView。 So, you need to check, is there is the first call. 因此,您需要检查是否有第一个电话。
Also, it is good practice to use custom UITableViewCell 另外,最好使用自定义UITableViewCell
Tableview is reusing created cells, so your approach is not the best. Tableview正在重用已创建的单元格,因此您的方法不是最佳方法。 What you are doing now is creating UIImageView everytime a cell is being used and if its a cells that is going to be reused you will create new UIImageView on top of your previous one. 您现在要做的就是每次使用一个单元格时都创建UIImageView,如果要重用它的单元格,您将在上一个单元格之上创建新的UIImageView。
I would suggest to do all this in interface builder. 我建议在界面生成器中执行所有这些操作。 If you dont want to, at least subclass UITableViewCell and create image view in init method of your cell, that will take care of overlapping UIImageviews over each other, but still consider using interface builder, its the easiest way to build tableviews. 如果您不想这样做,请至少将UITableViewCell子类化,并在单元格的init方法中创建图像视图,这将使UIImageviews彼此重叠,但仍要考虑使用接口构建器,这是构建表视图的最简单方法。
Here's some tutorial on tableviews in interface builder, this should help you get started: http://shrikar.com/blog/2015/01/17/uitableview-and-uitableviewcell-customization-in-swift/ 这是关于界面生成器中的表视图的一些教程,这应该可以帮助您入门: http : //shrikar.com/blog/2015/01/17/uitableview-and-uitableviewcell-customization-in-swift/
Good luck! 祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.