如何在Swift中以编程方式设置UITableView单元格高度?

9
如何以编程方式设置视图高度?我有以下代码:
cell.viewMain.frame = CGRectMake(cell.viewMain.frame.origin.x, cell.viewMain.frame.origin.y, cell.viewMain.frame.size.width, 65.0)

但是那并不起作用。

更新:

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
}

你在哪里设置这个?在哪个方法中? - JFAP
在tableView的cellForRowAtIndexPath方法中 - Rahmat Hidayat
我想用if条件语句制作动态大小。 - Rahmat Hidayat
你能展示一下运行这段代码的整个函数/方法吗?这样我们可以更好地帮助你。 - JFAP
好的,我已经更新了我的问题。 - Rahmat Hidayat
5个回答

8

6

首先,rowHeight属性会改变表格中所有行的高度。如果您需要为特定行实现特定高度,请使用tableView:heightForRowAtIndexPath:方法。请先从您的代码中删除tbUpdate.rowHeight


6
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    var cellHeight:CGFloat = CGFloat()

    if indexPath.row % 2 == 0 {
        cellHeight = 20
    }
    else if indexPath.row % 2 != 0 {
        cellHeight = 50
    }
    return cellHeight
}

确保在viewDidLoad中添加self.tableviewObj.delegate = self。 - user1090751

4

您可以尝试使用自动布局创建一个高度约束,然后将该约束连接到一个outlet。然后设置该约束的常量值,

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() 

将此代码放在cellForRowAtIndexPath中。
编辑:我误解了问题,认为是在cellView中添加另一个视图,如果是这样,那么像上面的答案所述,委托方法heightForRowAtIndexPath确实是正确的。
例如:
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat 
{
    if x == 0{
        return 100.0 //Choose your custom row height
    } else {
        return 50
    }
}

我更新了代码以适用于tableViewCells。你是说你想要一个动态大小的高度吗?还是所有单元格的高度都将固定? - Zayne ZH
我想用if条件语句制作动态大小。 - Rahmat Hidayat

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接