Some tableview cells with dynamic height, other with fixed height

匆匆过客 提交于 2019-12-02 12:31:09

问题


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.


回答1:


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.




回答2:


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
}



回答3:


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
     }
}


来源:https://stackoverflow.com/questions/47443494/some-tableview-cells-with-dynamic-height-other-with-fixed-height

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!