Bur*_*rak 35 uitableview ios autolayout
我在Xcode 5中使用autolayout.
我将表格视图的高度设置为大于或等于200px.我希望它具有动态大小.因为有时它会有很多行,有时它会有几行.
但大小总是200px.如果内容大于那个,我应该向下滚动以查看较低的行.
我该怎么做才能给tableview动态大小?
Jua*_*lan 65
这是使用最新版本的Xcode测试的.
1)在Xcode中转到故事板并单击表视图以选择它.
2)在"工具"窗格(参见图1)中,确保定义了表视图高度的约束.

3)在显示表视图的视图控制器中,为此约束创建一个插座:
在Swift 3中
@IBOutlet weak var dynamicTVHeight: NSLayoutConstraint!
Run Code Online (Sandbox Code Playgroud)
在目标C中
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *dynamicTVHeight;
Run Code Online (Sandbox Code Playgroud)
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()
}
Run Code Online (Sandbox Code Playgroud)
目标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];
}
Run Code Online (Sandbox Code Playgroud)
这应该可以解决您的问题.
这些是示例项目的两个版本的链接,它们可以满足您的需求,一个用于Objective C,另一个用于Swift 3.下载并使用Xcode进行测试.这两个项目都使用最新版本的Xcode,Xcode 8.3.2.
https://github.com/jcatalan007/TestTableviewAutolayout https://github.com/jcatalan007/TestTableviewAutolayoutSwift
| 归档时间: |
|
| 查看次数: |
45567 次 |
| 最近记录: |