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

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

有人能给我一些建议吗?


当前回答

如果你使用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在scrollview内部,所以我必须给高度约束为0。

然后在运行时,我做了以下更改,

       func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
            self.viewWillLayoutSubviews()
       }
    
       override func viewWillLayoutSubviews() {
            super.updateViewConstraints()
             DispatchQueue.main.async {
               self.tableViewHeightConstraint?.constant = self.myTableView.contentSize.height
               self.view.layoutIfNeeded()
          }
       }

我在iOS 7中尝试过这个功能,对我来说很有效

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.tableView sizeToFit];
}

如果你使用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;
    });

如果您希望您的表是动态的,您将需要使用一个基于上面所详述的表内容的解决方案。如果你只是想显示一个更小的表,你可以使用容器视图并在其中嵌入一个UITableViewController——UITableView将根据容器大小调整大小。

这避免了大量的计算和对布局的调用。