Some tableview cells with dynamic height, other with fixed height
Asked Answered
S

3

2

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.

Scarlet answered 22/11, 2017 at 20:36 Comment(0)
L
6

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.

Locate answered 26/11, 2017 at 4:8 Comment(4)
is it compulsory to implement delegate method "estimatedHeightForRowAt" ?Scarlet
First i tried without it & the result is not which i expected. i mean cell height is not expanding at all. Afterwards i tried with it & get the expected result which i wanted. I face same kind of problem & i solved it in this way.Locate
Its a too late response though. Did you find any better solution ? If you have then feel free to share.Locate
ok thanks for the response! I will try it and will let you know :)Scarlet
A
3

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
}
Amhara answered 22/11, 2017 at 20:43 Comment(1)
Swift 5 UITableView.automaticDimensionGarcon
N
1

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
     }
}
Namedropping answered 26/11, 2017 at 4:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.