gpt4 book ai didi

ios - 只能通过覆盖 heightForRowAtIndexPath 来更改静态 UITableViewCell 的高度?

转载 作者:搜寻专家 更新时间:2023-10-30 20:19:33 24 4
gpt4 key购买 nike

我查看了很多关于如何通过重写 heightForRowAtIndexPath 来隐藏静态 UITableViewCell 的示例,虽然我现在已经开始工作了,但它看起来太麻烦了我想看看我是否做错了什么。

我有一个 UITableViewController,它的 TableView 大约有 8 行。我的应用程序中的这个屏幕显示单个对象,例如一行是描述,一行是图像,一行包含 map View 等。所有行都是静态的。

在某些情况下,显示的某些对象没有 map ,因此我想隐藏包含 mapview 的行。由于它是一个静态行,我想通过为该行设置一个导出属性(例如 @property (weak, nonatomic) IBOutlet UITableViewCell *mapViewRow;),然后我可以以某种方式将该行的高度设置为0 或在 viewDidLoadviewWillAppear 中隐藏该行。然而,似乎唯一的方法是覆盖 heightForRowAtIndexPath 方法,这有点烦人,因为我需要在我的代码中硬编码 map 行的索引,例如

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == 6 && self.displayItem.shouldHideMap) {
return 0;
}
return [super tableView:tableView heightForRowAtIndexPath:indexPath];
}

当然,没什么大不了的,但是在 tableview 中调整 static 行大小的整个方法似乎与在 Storyboard 中设置它们的意义不符首先。

最佳答案

编辑 - 我的回答背后的理由

要更改行的高度,您必须重新加载整个表格或包含该行的子集。 B/c 在表格中有一行高度为零有点奇怪,我更喜欢修改您的数据源,使表格中不存在该行。

有很多方法可以做到这一点。您可以从 displayItem 构建一个数组,其中数组中的每一行对应于表中带有适当数据的一行。您将重建此数组,然后调用 [tableView reloadData]。我的原始答案还将通过将每个数据元素视为具有 0 或 1 行的部分来消除不需要的行。

原始答案

您的表格 View 是普通样式还是分组样式?如果它是普通样式,您可以将每一行视为一个部分,其中包含 0 行或 1 行。在您的 tableView 数据源和委托(delegate)方法中,您将使用部分索引来识别 self.displayItem 中您关心该部分的数据。

你的代码应该是这样的:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 8; // max number of possible rows in table
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger rows = 1;

// set self.mapSectionIndex during initialization or hard code it
if (section == self.mapSectionIndex && self.displayItem.shouldHideMap) {
rows = 0;
}
return rows;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:indexPath
{
return 60.0f; // whatever you want the height to be
}

// also modify tableView:cellForRowAtIndexPath: and any other tableView delegate and dataSource methods appropriately

关于ios - 只能通过覆盖 heightForRowAtIndexPath 来更改静态 UITableViewCell 的高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15915442/

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