【问题标题】:Changing height of individual cell UITableView更改单个单元格 UITableView 的高度
【发布时间】:2015-07-01 08:05:02
【问题描述】:

我想要以下内容:

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

    let cell = tableView.dequeueReusableCellWithIdentifier("NewsCell", forIndexPath: indexPath) as! UITableViewCell

    if indexPath == 3{

        cell.height = "50dp"

    }       

    return cell

}

解决此问题的替代方法或最简单的方法是什么?

编辑

我是否可以同时指定节号:即-

if sectionIndex == 5

【问题讨论】:

  • 读取表视图委托协议参考..

标签: ios swift uitableview


【解决方案1】:

我建议使用 heightForRowAtIndexPath 函数。 TableView 将调用此函数来确定特定索引路径的行高。

示例代码:

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    if indexPath.section == SECTION_INDEX {
        return 60
    } else {
        return UITableViewAutomaticDimension
    }
}

斯威夫特 4:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if indexPath.section == SECTION_INDEX {
        return 60
    } else {
        return UITableViewAutomaticDimension
    }
}

稍微解释一下: indexPath 有两个属性:section 和 row。通过检查这两个属性,您可以制作自己的控制流来确定每个单元格的高度。

如果返回 60,则表示您希望单元格的高度为 60 磅。如果您返回 UITableViewAutomaticDimension,您希望系统为您确定最佳高度(在这种情况下,您最好为情节提要中的单元格设置自动布局)。

我也建议你在 iTunes U 上学习斯坦福的 CS193p 课程,对你有很大帮助:)

【讨论】:

  • 这会迫使您为可能希望保持不变的单元格设置高度...我认为这就是 Moritz 没有选择答案的原因。
【解决方案2】:

最简单的方法是覆盖heightForRowAtIndexPath

  override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    let section = indexPath.section
    let row = indexPath.row
    if section == 0 && row == 2{
      return 50.0
    }
    return 22.0
  }

【讨论】:

    【解决方案3】:
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
       if indexPath.section == 5
       {
           if indexPath.row == 3
           {
               return 150.0
           }
       }
    
       return 200.0
    }
    

    【讨论】:

      猜你喜欢
      • 2012-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多