2016-09-27 94 views
0

我有一个分组的tableview和数据源如下所示:TableView中没有使用正确的TableViewCell

let customCell = UITableViewCell() 
customCell.textLabel?.text = "this is a custom cell" 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellA", for: indexPath) as! CellA 

    cell.label.text = "dummy text" 

    switch indexPath.section { 
    case 0 : 
     switch indexPath.row { 
     case 0 : cell.label.text = "Foo" 
     case 1 : cell.label.text = "Bar" 
     default: 
      fatalError("Row does not exist") 
     } 
    case 1 : 
     switch indexPath.row { 
     case 0 : return customCell 
     default: 
      fatalError("Row does not exist") 
     } 
    default: 
     fatalError("Section does not exist") 
    } 

    return cell 
} 

func numberOfSections(in tableView: UITableView) -> Int { return 2 } 

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    switch section { 
    case 0 : return 2 
    case 1 : return 1 
    default: 
     fatalError("Section does not exist") 
    } 
} 

问题:
我想第2节使用customCell而是它仍然使用的电池我使用方法dequeueReusableCell(identifier:,indexPath:)创建,具有虚拟文本"dummy text"。如果我使用方法,则不会发生这种情况:dequeueReusableCell(identifier:)(不含indexPath)。

这样做的正确方法是什么,或者我应该只使用没有indexPath的方法?

+0

你有没有调试来检查是否行'情况下0:返回customCell'是否达到? –

+0

你应该在'case 0'和'case 1'设置单元格文本标签数据。 – zsteed

+0

@BenjaminLowry:是的,我已经检查过,它确实到达了'case 0:'。 @zsteed:即使我这样做,出列的单元格将会在'customCell'之上。 –

回答

1

因此,您所做的事情几乎是正确的,您的customCell也正在添加到您的tableView。但是,这里发生的是,首先你是dequeueing一个单元cellForRowAt,然后检查section并返回cell。所以你的customCellindexPath.section = 1被添加,但dequeued单元格出现在它上面。你可以调试view hierarchy并查看魔法。

现在,你有你的cell创造移动到某个section,并从那里返回,像下面,它应该工作:

switch indexPath.section { 
     case 0: 
      let cell = tableVIew.dequeueReusableCellWithIdentifier("cellA", forIndexPath: indexPath) as! cellA 
      cell.textLabel?.text = "dummy text" 

      switch indexPath.row { 
       case 0 : 
        cell.textLabel?.text = "Foo" 
        return cell 
       case 1 : 
        cell.textLabel?.text = "Bar" 
        return cell 
      default: 
       fatalError("Row does not exist") 
      } 
     case 1: 
      switch indexPath.row { 
       case 0 : 
        return customCell 
      default: 
       fatalError("Row does not exist") 
      } 
     default: 
      fatalError("Section does not exist") 
    } 
+0

我之前没有检查过视图层次,你是对的。出列的单元格位于'customCell'的顶部。正如我所展示的,我实际上希望有一些方法可以做到这一点。我在这里使用的例子只有2个部分,但在我的原始项目中,我有更多的东西,就像你的答案。你也碰巧知道为什么这不会发生,当我使用dequeue方法**没有** indexPath? –

+0

根据API参考文档(XCode docs)中的文档,'代表用来获取已经分配的单元格,而不是分配一个新的单元格.'这是没有'indexPath'和'新的出队方法保证单元格是返回并正确调整大小,假设标识符是用'indexPath'注册的。所以你必须已经了解到,对于每个'indexPath'它都会寻找一个新的待出队/创建的单元。 – Santosh

相关问题