这是用最新版本的 Xcode 测试的。
1) 在 Xcode 中转到情节提要并单击您的表格视图以选择它。
2) 在 Utilities 窗格中(见图 1)确保定义了 table view 高度的约束。
3) 在显示表视图的视图控制器中,为该约束创建一个出口:
在 Swift 3 中
@IBOutlet weak var dynamicTVHeight: NSLayoutConstraint!
在目标 C 中
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *dynamicTVHeight;
4) 在情节提要中返回UITableView 的高度限制,并验证右侧的图标已将颜色从紫色变为蓝色(见图2)
4) 也将这段代码放在同一个视图控制器中:
斯威夫特
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let height = min(self.view.bounds.size.height, tableView.contentSize.height)
dynamicTVHeight.constant = height
self.view.layoutIfNeeded()
}
目标 C
- (void)viewWillAppear:(BOOL)animated
{
// just add this line to the end of this method or create it if it does not exist
[self.tableView reloadData];
}
-(void)viewDidLayoutSubviews
{
CGFloat height = MIN(self.view.bounds.size.height, self.tableView.contentSize.height);
self.dynamicTVHeight.constant = height;
[self.view layoutIfNeeded];
}
这应该可以解决您的问题。
这些是示例项目的两个版本的链接,可以满足您的需求,一个用于 Objective C,另一个用于 Swift 3。下载并使用 Xcode 进行测试。这两个项目都使用最新版本的 Xcode,Xcode 8.3.2。
https://github.com/jcatalan007/TestTableviewAutolayout
https://github.com/jcatalan007/TestTableviewAutolayoutSwift