我有一个包含 2 个部分的 tableview
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
switch (section) {
case 0: return @"s1";
case 1: return @"s2";
}
}
我想在第 0 部分添加标签。
-(void) tableView:(UITableView *)tableView willDisplayHeaderView(nonnull UIView *)view forSection:(NSInteger)section {
if (section == 0) {
for (UIView *subView in view.subviews) {
if (subView.tag == 99) {
[subView removeFromSuperview];
break;
}
}
UITableViewHeaderFooterView *headerView = (UITableViewHeaderFooterView *)view;
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake([[UIScreen mainScreen] bounds].size.width - 150 - headerView.textLabel.frame.origin.x, headerView.textLabel.frame.origin.y, 150, hederView.textLabel.frame.size.height)];
label.text = @"test";
label.tag = 99;
[headerView addSubview:label];
}
}
初始显示工作正常。
然后我使用 presentViewController 弹出相机图像选择器,但每当我关闭图像选择器并返回到当前 View 时,“测试”标签将同时出现在第 0 节和第 1 节中。
这意味着在两个部分中都会有 2 个“测试”。
如果我用
if (section == 1) {
for (UIView *subView in view.subviews) {
if (subView.tag == 99) {
[subView removeFromSuperview];
break;
}
}
}
这将从第 1 部分中删除额外的“测试”。
有什么可能的原因吗?我尝试调试但看不出任何有用的信息来解释为什么会发生这种情况,因为在 if (section == 0) block 运行完成后,它将进入汇编模式,如果我从中断继续运行,第 1 节将显示“测试",我不知道它来自哪里。
我不是在寻求解决方案(我有一个,只是为了从第 1 部分中删除标签 99 标签),我是在寻求原因以及我做错的任何地方。
任何建议将不胜感激。非常感谢。
最佳答案
您第一次实例化
UITableViewController
类时,TableView
会为您的两个部分重新加载两个不同的 View 。当您返回同一个 UITableViewController
时,不会实例化一个新实例。但是您可能在 viewWillAppear
或 viewDidAppear
中有一个 reloadData()
调用。现在,TableView
重新加载了以前的 views
,并为您的 Headers
重用。先前实例化中第 1 部分的 View 1 现在变为第 0 部分的 View 。(此时您将 UILabel
添加为此 View 1 的 subView
)先前实例化的 View 0 变为现在是第 1 部分的 View 。(它已经有来自先前实例化的 subView
标签)。因此,当您返回到同一个 TableViewController
并且由于它没有再次实例化时, header 的两个 View 都有标签 subView
您可以避免 reloadData()
从 View 中调用,它看起来很好,或者遵循覆盖
方法的最佳实践
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
关于ios - 将 subview 添加到 headerview : added to a wrong section,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36418422/