我正在创建一个应用程序,它将在UILabel中有一个问题,并在UITableView中显示多项选择的答案,每行显示多项选择。问题和答案会有所不同,所以我需要这个UITableView的高度是动态的。

我想为桌子周围找一个合适的尺寸。其中,表的框架被设置为所有内容的高度。

有人能给我一些建议吗?


当前回答

Swift 3, iOS 10.3

解决方案1: 只需将self.tableview.sizeToFit()放在cellForRowAt indexPath函数中。确保tableview的高度比你需要的高。 如果tableview下面没有视图,这是一个很好的解决方案。然而,如果你有,底部tableview约束将不会更新(我没有尝试修复它,因为我想出了解决方案2)

例子:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCell(withIdentifier: "TestCell", for: indexPath) as? TestCell {
        cell.configureCell(data: testArray[indexPath.row])
        self.postsTableView.sizeToFit()
        return cell
    }

    return UITableViewCell()
}

解决方案2: 在故事板中设置tableview高度约束,并将其拖到ViewController中。如果你知道单元格的平均高度,也知道数组包含多少元素,你可以这样做:

tableViewHeightConstraint.constant = CGFloat(testArray.count) * 90.0     // Let's say 90 is the average cell height

*编辑:

在我尝试了所有的解决方案之后,每个解决方案都解决了一些问题,但不是完全解决了问题,这个答案解释并完全解决了这个问题。

其他回答

快速解决方案

遵循以下步骤:

从故事板中为表设置高度约束。 从故事板中拖动高度约束,并在视图控制器文件中为它创建@IBOutlet。 @IBOutlet var tableHeight: NSLayoutConstraint! 然后你可以使用下面的代码动态地改变表的高度: override func viewWillLayoutSubviews() { super.updateViewConstraints () self.tableHeight ?。常量= self.table.contentSize.height }

如果最后一行被切断,尝试在willDisplay单元格函数中调用viewWillLayoutSubviews():

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    self.viewWillLayoutSubviews()
}

如果你使用AutoLayout,有一个更好的方法:改变决定高度的约束。只需计算表内容的高度,然后找到约束并更改它。下面是一个例子(假设决定表高度的约束实际上是一个关系为“Equal”的高度约束):

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    for constraint in tableView.constraints {
        if constraint.firstItem as? UITableView == tableView {
            if constraint.firstAttribute == .height {
                constraint.constant = tableView.contentSize.height
            }
        }
    }
}

事实上,我自己找到了答案。

我只是为tableView.frame创建了一个新的CGRect,它的高度是table.contentSize.height

那将UITableView的高度设置为它内容的高度。 因为代码修改了UI,所以不要忘记在主线程中运行它:

dispatch_async(dispatch_get_main_queue(), ^{
        //This code will run in the main thread:
        CGRect frame = self.tableView.frame;
        frame.size.height = self.tableView.contentSize.height;
        self.tableView.frame = frame;
    });

如果你的contentSize是不正确的,这是因为它是基于估计的rowheight(自动),使用这个之前

tableView.estimatedRowHeight = 0;

来源:https://forums.developer.apple.com/thread/81895

在swift 3中解决这个问题的方法:在viewDidAppear中调用这个方法

func UITableView_Auto_Height(_ t : UITableView)
{
        var frame: CGRect = t.frame;
        frame.size.height = t.contentSize.height;
        t.frame = frame;        
}