首页 文章

具有异常的动态UITableViewCell高度

提问于
浏览
1

我试图动态设置我的自定义单元格的高度 . 我使用下面的代码,它的工作原理 .

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = view.frame.height / 4

但是,我需要索引0(第一个单元格)的表视图作为具有固定高度的 Headers ,其余单元格具有动态高度 .

我试过这个:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    if indexPath.row == 0 {
        return (self.view.frame.height/2)
    }
    return tableView.estimatedRowHeight
}

但这只是设置我在viewDidLoad()中设置的estimatedRowHeight的高度

我怎样才能使索引0的第一行高度为屏幕的1/2

view.frame.height / 2

而其余的细胞动态地改变高度 . 谢谢您的帮助!

2 回答

  • 0

    对于indexPaths大于0的单元格,我认为你需要从 heightForRowAtIndexPath 方法返回 tableView.rowHeight 而不是 tableView.estimatedRowHeight

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
      if indexPath.row == 0 {
        return (self.view.frame.height / 2)
      }
      return tableView.rowHeight // or return UITableViewAutomaticDimension
    }
    
  • 1

    ozgur给了我一些我需要弄明白的暗示 .

    而不是在viewDidLoad()中设置tableView.row高度,我将其移动到cellForRowAtIndexPath

    if indexPath.row == 0 {
        tableView.rowHeight = view.frame.height / 2
    
        ...
    
        return cell
    } else {
    
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = view.frame.height / 4
    
        ...
    
        return cell
    }
    

    编辑:没关系 . 这实际上不起作用,因为第一个单元格位于索引0,当它尝试创建该单元格时,tableView将所有行高度设置为view.frame.height / 2

相关问题