Search code examples
iosswiftuitableviewtableviewrow-height

Some tableview cells with dynamic height, other with fixed height


I have a tableview. I want some tableview cells with dynamic height while other cells with the fixed height. For dynamic height, I used following lines in my viewDidLoad view controller delegate.

tableView.estimatedRowHeight = 200
tableView.rowHeight = UITableViewAutomaticDimension

what will be the efficient way to have fixed heighted cells and self sizing cells in one tableview?

Thanks in advance.


Solution

  • Swift 3

    You can retrun dynamic & static cell height in a tableview by doing this

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    
        if indexPath.row == 0 {
            return 120.0 // for static cell height
        }
        else {
            return UITableViewAutomaticDimension // for dynamic cell height
        }
    }
    

    You have to implement another tableview estimatedHeightForRowAt method like that

    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    
        if indexPath.row == 0 {
            return 120.0
        }
        else {
            return UITableViewAutomaticDimension
        }
    }
    

    Don't forget to set label lineNumbers to 0 & lineBreakMode which label will expand dynamically & most importantly don't set the label height fixed.