【问题标题】:Add A UITableView Cell After Another One在另一个之后添加一个 UITableView 单元格
【发布时间】:2021-01-16 16:26:54
【问题描述】:

基本上我有一个包含两种单元格的表格视图。一个是包含从数组中提取的数字的单元格。第二个单元格应该充当间隔单元格,但可以包含信息。但是,我只看到第二个单元格位于第一个单元格之后的解决方案,前提是它的行等于 0 或被分割。

数字数组是 [1,2,3,4,5,6,7],第一个单元格类型从中拉出以显示每个数字

我正在尝试获得如下所示的内容:

细胞类型:1

细胞类型二

细胞类型:2

细胞类型二

细胞类型:3

细胞类型二

细胞类型:4

细胞类型二

...等等。

我想过尝试让空间单元在每个下一个单元之后出现,但我认为这没有意义。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    let index = indexPath.row
  
   
    if index >= 0 {
    
    let cell = tableView.dequeueReusableCell(withIdentifier: "productsblock", for: indexPath ) as! DetailTBCell


        return cell
     
    }
    else {
    
          let spacecell = tableView.dequeueReusableCell(withIdentifier: "spacingcell", for: indexPath ) as! DetailSpaceTBCell
        
        return spacecell

 
}

}

这会打印数组中的所有数字并显示它们,但第二个单元格根本不显示。

我不确定该做什么或如何让它发挥作用。

【问题讨论】:

    标签: ios arrays swift uitableview


    【解决方案1】:

    如果您注意到您的产品单元格需要显示在偶数位置,而间距单元格需要显示在奇数位置。

    `index >= 0 ` needs to replaced with `index % 2 == 0 `
    

    此外,为了从产品数组中获取数据,您需要将索引除以 2。

    let products = [1,2,3,4,5,6,7]
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    let index = indexPath.row
    
    
    if index % 2 == 0 {
    
    let cell = tableView.dequeueReusableCell(withIdentifier: "productsblock", for: indexPath ) as! DetailTBCell
    
        // Fetching data from array products defined above
        let data = products[index / 2]
        return cell
     
    }
    else {
    
          let spacecell = tableView.dequeueReusableCell(withIdentifier: "spacingcell", for: indexPath ) as! DetailSpaceTBCell
        
        return spacecell
    

    }

    【讨论】:

      【解决方案2】:

      if (index % 2) == 0 |尝试如果索引号是双放第一个 tableCell 否则放另一个

      func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
          
          let index = indexPath.row
        
         
          if (index % 2) == 0 {
          
          let cell = tableView.dequeueReusableCell(withIdentifier: "productsblock", for: indexPath ) as! DetailTBCell
      
      
              return cell
           
          }
          else {
          
                let spacecell = tableView.dequeueReusableCell(withIdentifier: "spacingcell", for: indexPath ) as! DetailSpaceTBCell
              
              return spacecell
      
       
      }
      

      【讨论】:

      • 我尝试过类似的方法。发生的事情是它像其他细胞一样做第一种细胞。所以它看起来像 1 个空间单元 3 个空间单元 5 个空间单元等,因为它跳过了其余部分。但是,我正在尝试实现返回数组的所有元素并且间距单元格位于数组中的每个数字之后的结果。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多