这是使用最新版本的 Xcode 进行测试的。
1) 在 Xcode 中,转到故事板并单击表视图以选择它。
2) 在“实用工具”窗格中(参见图 1),确保定义了表格视图高度的约束。
3) 在显示表视图的视图控制器中创建此约束的出口:
在 Swift 3 中
@IBOutlet weak var dynamicTVHeight: NSLayoutConstraint!
在 Objective C 中
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *dynamicTVHeight;
4) 在故事板中返回高度约束UITableView
并验证右侧图标的颜色是否已从紫色变为蓝色(见图2)
4)同样将此代码放在同一个视图控制器中:
Swift
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/TestTableviewAutolayout
https://github.com/jcatalan007/TestTableviewAutolayoutSwift https://github.com/jcatalan007/TestTableviewAutolayoutSwift