Some tableview cells with dynamic height, other with fixed height

為{幸葍}努か 提交于 2019-12-02 07:13:43

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.

Swift 4

You can use the indexPath from this function to return fixed height for certain rows and dynamic height for others.

// UITableViewAutomaticDimension calculates height of label contents/text
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

Suppose, indexPath.row = 0 and 1 contains static height and dynamic height respectively, then

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat 
{
     if indexPath.row == 0 {
        return 120
     } else {
        return UITableViewAutomaticDimension
     }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!