2016-06-15 102 views
0

我有一个分组的tableview由两行组成,每行都有一个自定义的tableview单元格。我有定制的tableview类和单元格标识符全部建立并与界面构建器中的tableview行相关联。我的第一个tableview单元格显示正常,但第二个似乎具有与第一个单元格相同的属性。但是,一旦我点击第二个单元然后点击第一个单元,第二个单元切换到正确的单元设计。UITableView与两个自定义单元格没有正确显示

override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    return 1 
} 

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return 2 
} 

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("EditCellID", forIndexPath: indexPath) as! EditCell 
    if indexPath.row == 0 
    { 
     //Do some stuff 
     return cell 
    } 
    if indexPath.row == 1 
    { 
     let cell = tableView.dequeueReusableCellWithIdentifier("DeleteCellID", forIndexPath: indexPath) as! DeleteCell 
     //Do some stuff 
     return cell 
    } 

    return cell 
} 

回答

0

试试这个:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell: UITableViewCell! 

    if indexPath.row == 0 { 
     cell = tableView.dequeueReusableCellWithIdentifier("EditCellID", forIndexPath: indexPath) as! EditCell 
     // Now you can access the subclass attributes by doing : (cell as! EditCell).theAttribute 
    } else { 
     cell = tableView.dequeueReusableCellWithIdentifier("DeleteCellID", forIndexPath: indexPath) as! DeleteCell 
    } 

    return cell 
} 

创建只有一个范围单元对象,并根据该行,初始化对象作为一个特定的UITableViewCell子类的实例。

更新:添加了关于如何访问UITableViewCell子类属性的评论。

+0

有道理,但当我尝试在第一个if语句中设置单元格属性时出现错误。例如,EditCell有一个'UITextField IBOutlet',但是当我设置它的时候,我得到一个错误,说'类型UITableViewCell的Value没有成员titleField'。出于某种原因,单元格停留在“UITableViewCell”类型而不是“EditCell” – Brosef

+0

对不起,忘记将此珍闻添加到我的答案中。只要这样做:'(cell as!EditCell).titleField' – Lucas

+0

哇!工作完美,但为什么'(cell as!EditCell).titleField'必要?我们没有将这个单元格作为EditCell在此行中移动:cell = tableView.dequeueReusableCellWithIdentifier(“EditCellID”,forIndexPath:indexPath)as! EditCell'? – Brosef

相关问题