ios 更改单个单元格的高度UITableView

dffbzjpn  于 2022-11-26  发布在  iOS
关注(0)|答案(5)|浏览(166)

我想要类似以下的东西:

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

}

有什么替代的或最简单的方法去做这件事?

编辑

我是否可以同时指定章节编号:i.e-

if sectionIndex == 5
vjrehmav

vjrehmav1#

我建议使用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有两个属性:通过检查这两个属性,您可以创建自己的控制流来确定每个单元格的高度。
如果返回60,则表示希望单元格的高度为60磅;如果返回UITableViewAutomaticDimension,则表示希望系统为您确定最佳高度(在这种情况下,最好为情节提要中的单元格设置自动布局)。
我还建议你在iTunes U上参加斯坦福大学课程CS 193 p,这对你会有很大的帮助:)

mfuanj7w

mfuanj7w2#

最简单的方法是覆盖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
  }
nzk0hqpo

nzk0hqpo3#

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
   if indexPath.section == 5
   {
       if indexPath.row == 3
       {
           return 150.0
       }
   }

   return 200.0
}
vkc1a9a2

vkc1a9a24#

以下是朱胜祺的回答,Swift 5+的代码。

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

wn9m85ua5#

最简单的方法是重写tableview中的heightForRowAtIndexPath委托方法.这些方法会根据内容自动改变高度.

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    
    return UITableView.AutoDiemensions
  }

相关问题