Заголовок раздела UITableView исчезает, если я вставляю или удаляю строки
У меня есть UITableView
с 4 разделами. Три из этих разделов имеют заголовок.
Представление заголовка - это UITableViewCell
, которое я де-очереди в качестве нормальной ячейки в делегате viewForHeaderInSection:
.
Если я вставляю или удаляю строку из любого раздела, исчезают другие ячейки заголовка tableview
.
Я предполагаю, что это имеет какое-то отношение к повторному использованию ячеек, однако сначала все ячейки отображаются на экране (одновременно отображаются все три заголовка на экране).
Я попытался перезагрузить другие разделы после вставки или удаления, но это не помогает.
Вот код:
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
switch (section) {
case kSectionCardInformation:
case kSectionContactInformation:
case kSectionTags: {
static NSString *CellIdentifier = @"EditContactHeaderCell";
EditContactHeaderCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
return cell;
}
default:
return nil;
}
}
И вот где я удаляю строку в разделе revelant:
- (void)deleteTag:(CDTag *)tag {
[self.tableView beginUpdates];
NSMutableArray *objects = [self.sections objectAtIndex:kSectionTags];
if ([objects containsObject:tag]) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[objects indexOfObject:tag] inSection:kSectionTags];
[objects removeObject:tag];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationMiddle];
[self.contact deleteTag:tag];
}
[self.tableView endUpdates];
}
Любая помощь, очень ценная.
Ответы
Ответ 1
Просто оберните UITableViewCell в UIView.
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
switch (section) {
case kSectionCardInformation:
case kSectionContactInformation:
case kSectionTags: {
static NSString *CellIdentifier = @"EditContactHeaderCell";
EditContactHeaderCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UIView * view = [[[UIView alloc] init] autorelease];
[view addSubview:cell];
//setup the view frame: fixed, autolayout, ...
return view;
}
default:
return nil;
}
}
Ответ 2
Добавление комментария, поскольку у меня была та же проблема... Проблема заключалась в том, что я тоже использовал UITableViewCell в качестве заголовка вместо использования UITableViewHeaderFooterView.
Чтобы устранить проблему:
- Создайте файл nib и создайте свой собственный заголовок там, а не внутри UITableView на вашем раскадровке.
- Свяжите его со своим пользовательским классом UITableViewHeaderFooterView
-
Зарегистрируйте этот элемент внутри функции viewDidLoad
override func viewDidLoad() {
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.register(UINib(nibName: "NibFileName", bundle: nil), forHeaderFooterViewReuseIdentifier: "CustomViewHeaderView")
}
-
Отмените повторно используемый HeaderFooterView из функции viewForHeaderInSection:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let cell = tableView.dequeueReusableHeaderFooterView(withIdentifier:"CustomViewHeaderView") as! CustomViewHeaderView
return cell
}
Это фиксировало мой исчезающий заголовок. Надеюсь, это поможет другим.
Ответ 3
Для Swift 4
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let containerView = UIView()
guard let headerCell = tableView.dequeueReusableCell(withIdentifier: "MyHeaderView") as? MyHeaderView else { fatalError(" Failed to load MyHeaderView") }
containerView.addSubview(headerCell)
return containerView
}
Ответ 4
Правильный способ решения этой проблемы - использовать UITableViewHeaderFooterView вместо использования UITableViewCell для раздела заголовка. Как @Francois Nadeau ответил.
Для получения более подробной информации о том, как использовать UITableViewHeaderFooterView для раздела заголовка, смотрите этот ответ: fooobar.com/questions/313912/...
Ответ 5
Я не знаю, почему вы используете ячейку tableview для заголовка, но я полагаю, что
Вы пропустили оператор break
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
switch (section) {
case kSectionCardInformation:
break;
case kSectionContactInformation:
break;
case kSectionTags: {
static NSString *CellIdentifier = @"EditContactHeaderCell";
EditContactHeaderCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
return cell;
}
default:
return nil;
}
}
Проверьте условие nil
перед возвратом ячейки, если оно было nil, тогда создайте ячейку.
static NSString *CellIdentifier = @"EditContactHeaderCell";
EditContactHeaderCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
return cell ?: createdCellNewly;
Обновление:
Затем проверьте, что ваш метод numberOfSectionsInTableView:(UITableView *)tableView
возвращает правильный счет.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// returning count is correct?
}
Проверьте и установите делегат таблицы и источник данных.