SWIFT:表格视图中的 2 个自定义单元格。怎么了?

Posted

技术标签:

【中文标题】SWIFT:表格视图中的 2 个自定义单元格。怎么了?【英文标题】:SWIFT: 2 custom cell in tableview. What's wrong? 【发布时间】:2015-02-18 15:54:33 【问题描述】:

我想在TableView 中放入 2 个自定义单元格,但我有一个小问题。我试图在 Google 和 *** 中找到答案,但答案对我没有帮助。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 

    if indexPath.row == 0
        var cell: CustomCell = tableView.dequeueReusableCellWithIdentifier("FistCustomTableViewCell", forIndexPath: indexPath) as CustomCell
        //set cell2
    
    if indexPath.row >= 1
        var cell: CustomCell = tableView.dequeueReusableCellWithIdentifier("CustomTableViewCell", forIndexPath: indexPath) as CustomCell
        let cons = aArray[indexPath.row - 1]
        // set cell2 
    
    return cell // (!) Use of unresolved identifier "cell"

【问题讨论】:

您能否详细说明“2 个自定义单元格”的含义?你想完成什么? 我的意思是我想在tableview中有两种不同类型的自定义单元格 @Maxim Globak 请在每个单元格中指定您希望获得更多信息的内容,并请显示您的 CustomCell 如果您想要两种不同类型的自定义单元格,为什么要两次都将同一个类 CustomCell 出列? 【参考方案1】:

需要在外面绘制单元格声明:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 

  var cell: CustomCell!
  if indexPath.row == 0
    cell = tableView.dequeueReusableCellWithIdentifier("FistCustomTableViewCell", forIndexPath: indexPath) as CustomCell
    //set cell2
  
  if indexPath.row >= 1
    cell = tableView.dequeueReusableCellWithIdentifier("CustomTableViewCell", forIndexPath: indexPath) as CustomCell
    let cons = aArray[indexPath.row - 1]
    // set cell2 
  
  return cell

【讨论】:

个别来说,一切正常,单元格在正确的类中描述,但是当我尝试连接所有时,我失败了。 if 语句中声明它超出范围 在这种情况下: where "return cell" // (!) 变量 "Cell" 在被初始化之前使用 血雨燕。只需给它一个像var cell = CustomCell() 这样的初始化或使用一个可选的。查看我添加的“!” @ThomasKilian 我的项目中有类似的要求,需要在表格中显示 2 个不同的单元格。我试图通过在表格中定义 2 个原型来展示它们。但它不工作。这是我关注的链接:***.com/questions/30774671/…【参考方案2】:

您必须在 if 语句中声明单元格。

【讨论】:

以上是关于SWIFT:表格视图中的 2 个自定义单元格。怎么了?的主要内容,如果未能解决你的问题,请参考以下文章

在 CollectionView 中添加第二个自定义单元格 - Swift

如何在swift ios中的两个自定义表格视图单元格之间添加间距?

使用自定义表格视图单元格中的故事板segue

防止在表格视图Swift中重用自定义单元格

Swift - 表格视图中的单元格出现在另一个单元格上

使用 swift 创建自定义的表格视图单元格