正确使用UITableViewController的方法

时间:2016-09-12 02:21:45

标签: swift

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    var renderWidth:CGFloat = 8
    var renderYPosition:CGFloat = 22
    let cell = tableView.dequeueReusableCellWithIdentifier("idcell", forIndexPath: indexPath) as! UITableViewCell
    let date = UILabel(frame: CGRectMake(renderWidth, renderYPosition, 110, 20))
    let dateText = "asdasdasdsad"
    date.text = dateText
    if(cell.selected){
        date.textColor = UIColor.whiteColor()
    }
    cell.addSubview(date)
    renderWidth = renderWidth + 110
}

如果我要显示三种类型的行(例如,单选按钮,文本标签,文本视图),则显示这些行的索引路径是完全动态的。所以我在cellForRowAtIndexPath中添加一些if case来确定它应该显示哪种类型的行。我将使用addsubview来做到这一点。但是,我看到一些帖子提到我们不应该在cellForRowAtIndexPath中添加子视图。我无法得到它。那有什么替代方案吗?这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

可重复使用的单元格应该是相同的 - 所以在你的情况下你应该制作三个不同的单元格模型,并在cellForRowAtIndexPath中让你的逻辑确定你要出列的单元格(确保你先在tableview中注册单元格) )。这样您就不必添加子视图,您可以根据需要配置单元格。这是更简洁的方法(也可能考虑使用viewmodel配置单元格)。