How can I adjust the height of a UITableView cell programmatically in Swift

How to set presentation height programmatically I tried this code

cell.viewMain.frame = CGRectMake(cell.viewMain.frame.origin.x, cell.viewMain.frame.origin.y, cell.viewMain.frame.size.width, 65.0)

But that does not work.

UPDATE:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("updateCell", forIndexPath: indexPath) as! UpdateCell

    if self.data[indexPath.row] == "b" {
        tbUpdate.rowHeight = 85
        cell.viewMain.frame = CGRectMake(cell.viewMain.frame.origin.x, cell.viewMain.frame.origin.y, cell.viewMain.frame.size.width, 65.0)
    }else{
        tbUpdate.rowHeight = 220
        cell.viewMain.frame = CGRectMake(cell.viewMain.frame.origin.x, cell.viewMain.frame.origin.y, cell.viewMain.frame.size.width, 200.0)
    }

    return cell
}
+4
source share
4 answers

first, rowHeight changes the height of all rows in your table. if you need a certain height for certain rows, use the method tableView:heightForRowAtIndexPath:. first remove tbUpdate.rowHight in your code.

+4
source

TableView elements have a height set in the form of a table.

You need to implement UITableViewDelegate tableView:heightForRowAtIndexPath:.

+2
source

, constrait, . ,

var y: Float
if x==0{ //some condition
    y = 10
}else if x==1{ //some condition
    y = 20
}
cell.viewMainHeightConstraint.constant = y 
cell.view.layoutIfNeeded() 

Put this in your cellForRowAtIndexPath

Edit: I misinterpreted the question as requesting another view in cellView, if so, the delegate method heightForRowAtIndexPath is really right, as indicated in the answer above.

Example:

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat 
{
    if x == 0{
        return 100.0 //Choose your custom row height
    } else {
        return 50
    }
}
+1
source
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        var height:CGFloat = CGFloat()
        if indexPath.row == 0 {
            height = 80
        }
        else if indexPath.row == 1 {
            height = self.view.frame.size.height - 44 - 64 // 44 is a tab bar height and 64 is navigationbar height.
            print(height)
        }
        return height
    }
0
source

Source: https://habr.com/ru/post/1653386/


All Articles