【问题标题】:Using TableView first cell as header and issues使用 TableView 第一个单元格作为标题和问题
【发布时间】:2015-11-02 07:11:16
【问题描述】:

我使用 tableview 的第一个单元格作为标题,例如在cellForRowAtIndexPath:

if indexPath.row == 0 {
cell.label.text = "Header"

}else {

// fill up the data 
cell.label.text = array[indexPath.row]
}

numberOfRowsInSection 我要返回这个:

return array.count

假设我的数组中有 20 个元素,我将第一个单元格保留为标题,因此其中一个元素将被删除。如果我增加了 array.count + 1array[indexPath.row + 1] 来解决这个问题,那么我的数组就会越界。我只想使用第一个单元格作为标题,其余数据在接下来的 20 个单元格中。为什么这不能发生!

【问题讨论】:

    标签: ios objective-c arrays uitableview


    【解决方案1】:

    我认为你的意思是使用array[indexPath.row - 1]

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        if indexPath.row > 0 {
            let entry = array[indexPath.row - 1]
        } else {
            //Configure the placeholder cell
        }
    }
    

    【讨论】:

      【解决方案2】:

      你应该在你的数组中放置一个占位符作为标题,然后 array.count 将包含标题,并且可以使用indexPath.row 正确索引占位符,这样你就不会出现越界错误

      否则,如果这不是一个选项,则在索引数组时必须破例,就像

      //psuedo code
      if (indexPath.row == 0) {
        return headerCell;
      }
      else {
        data = array[indexPath.row-1];
      
        return normalCell;
      }
      

      【讨论】:

        【解决方案3】:

        获取数据后,应为数据中的表头创建一个空对象。

        [array insertObject:@"header" atIndex:0];

        【讨论】:

          【解决方案4】:

          恕我直言,获取数组的第一个元素、创建自定义标题视图并将其从数组中删除会更容易,因此您只需使用数组中的内容处理普通的“uitableviewcells”,而无需需要使用任何条件。有一个 'delegate' 可以设置 'uitableviewheader' ,这也应该是放置它的地方。

          【讨论】:

            【解决方案5】:

            你可以用两种方式来做到这一点

            首先是

            if (indexPath.row == 0 )
            {
               cell.textLabel.text = @"Header";
            } 
            else {
               cell.textLabel.text = array[indexPath.row - 1];
               NSLog(@"The cell index is - %@",array[indexPath.row - 1]);
            }
            

            其次是

            if (indexPath.row > 0 )
            {
                cell.textLabel.text = array[indexPath.row - 1];
                NSLog(@"The cell index is - %@",array[indexPath.row - 1]);
            } 
            else 
            {
              cell.textLabel.text = @"Header";
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2016-09-03
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多