gpt4 book ai didi

ios - 如何使用自动布局功能使 UITableView 的高度动态化?

转载 作者:IT王子 更新时间:2023-10-29 07:43:12 26 4
gpt4 key购买 nike

我在 Xcode 5 中使用自动布局。

我将表格 View 的高度设置为大于或等于 200 像素。我希望它具有动态大小。因为有时它会有很多行,有时它会有几行。

但大小始终为 200px。如果内容比那个大,我应该向下滚动以查看下面的行。

我应该怎么做才能给tableview动态大小? enter image description here

最佳答案

这是用最新版本的 Xcode 测试的。

1) 在 Xcode 中转到 Storyboard并单击 TableView 以将其选中。

2) 在“实用程序” Pane 中(参见图片 1),确保定义了表格 View 高度的约束。

Table view heigth constraint

3) 在显示 TableView 的 View Controller 中为该约束创建一个导出:

在 swift 3 中

@IBOutlet weak var dynamicTVHeight: NSLayoutConstraint!

在 objective-c 中

@property (strong, nonatomic) IBOutlet NSLayoutConstraint *dynamicTVHeight;

4) 在 Storyboard 中,返回到 UITableView 的高度约束,并验证右侧的图标是否已将颜色从紫色更改为蓝色(见图 2)

Table view heigth constraint after outlet

4) 也将这段代码放在同一个 View Controller 中:

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()
}

objective-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

关于ios - 如何使用自动布局功能使 UITableView 的高度动态化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18498098/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com