UITableView: скрыть заголовок из пустого раздела
у меня есть UITableView, который отображает расходы с текущего месяца (см. скриншот):
моя проблема с заголовком для пустых разделов. есть ли способ спрятать их?
Данные загружаются из coredata.
это код, который генерирует заголовок название:
TitleForHeader
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
if ([tableView.dataSource tableView:tableView numberOfRowsInSection:section] == 0) {
return nil;
} else {
NSDate *today = [NSDate date ];
int todayInt = [dataHandler getDayNumber:today].intValue;
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:(-(todayInt-section-1)*60*60*24)];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:[[NSLocale preferredLanguages] objectAtIndex:0]]];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *formattedDateString = [dateFormatter stringFromDate:date];
return formattedDateString;}
}
ViewForHeader
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
if ([tableView.dataSource tableView:tableView numberOfRowsInSection:section] == 0) {
return nil;
} else {
UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 312, 30)];
UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(4, 9, 312, 20)];
UIView *top = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 312, 5)];
UIView *bottom = [[UIView alloc]initWithFrame:CGRectMake(0, 5, 312, 1)];
[top setBackgroundColor:[UIColor lightGrayColor]];
[bottom setBackgroundColor:[UIColor lightGrayColor]];
[title setText:[expenseTable.dataSource tableView:tableView titleForHeaderInSection:section]];
[title setTextColor:[UIColor darkGrayColor]];
UIFont *fontName = [UIFont fontWithName:@"Cochin-Bold" size:15.0];
[title setFont:fontName];
[headerView addSubview:title];
[headerView addSubview:top];
[headerView addSubview:bottom];
return headerView;
}
}
heightForHeader
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
NSLog(@"Height: %d",[tableView.dataSource tableView:tableView numberOfRowsInSection:section] == 0);
if ([tableView.dataSource tableView:tableView numberOfRowsInSection:section == 0]) {
return 0;
} else {
return 30;
}
}
numberOfRowsInSection
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int rows = 0;
for (Expense* exp in [dataHandler allMonthExpenses]) {
if ([exp day].intValue == section) {
rows++;
}
}
return rows;
}

Себастьян
7 ответов:
что делать, если в –
tableView:viewForHeaderInSection:выreturn nilесли количество секций равно 0.EDIT : Вы можете использовать
numberOfRowsInSectionдля получения количества элементов в разделе.EDIT: Вероятно, вы должны вернуть nil также в
titleForHeaderInSectionеслиnumberOfRowsInSectionравен 0.EDIT: Вы реализовали следующий метод?
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)sectionEDIT:Swift 3 пример
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: if self.tableView(tableView, numberOfRowsInSection: section) > 0 { return "Title example for section 1" } case 1: if self.tableView(tableView, numberOfRowsInSection: section) > 0 { return "Title example for section 2" } default: return nil // when return nil no header will be shown } return nil }
вы должны установить
tableView:heightForHeaderInSection:0 для соответствующих разделов. Это то, что изменилось довольно недавно и привело меня в пару мест. ОтUITableViewDelegateОн говорит...до iOS 5.0 табличные представления автоматически изменяли размеры высот заголовков до 0 для разделов, где tableView:viewForHeaderInSection: вернулся нулевой вид. В iOS 5.0 и более поздних версиях необходимо вернуть фактическое значение высота для каждого заголовка раздела В этом методе.
Так ты нужно сделать что-то вроде
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { if ([tableView.dataSource tableView:tableView numberOfRowsInSection:section] == 0) { return 0; } else { // whatever height you'd want for a real section header } }
в моей странной ситуации я должен вернуть:
viewForHeaderInSection - > nil
viewForFooterInSection - > nil (не забывайте о нижнем колонтитуле!)
heightForHeaderInSection ->0.01 (не ноль!)
heightForFooterInSection - > 0.01
только в этом случае пустые разделы исчезают полностью
взгляните на метод
-[UITableViewDelegate tableView:heightForHeaderInSection:]. Особенно примечание, которое сопровождает его документацию:до iOS 5.0 табличные представления автоматически изменяли размеры высот заголовки для 0 для разделов, где
tableView:viewForHeaderInSection:вернулnilвид. В iOS 5.0 и более поздних версиях необходимо вернуть фактическое значение высота для каждого заголовка раздела В этом методе.
Я знаю, это старый вопрос, но я хотел бы добавить к ней. Я предпочитаю подход установки
titleHeaderк нулю над изменениемheightForHeaderInSectionдо 0, так как это может вызвать проблемы сindexPathбыть +1 от того, где это должно быть из-за заголовка все еще там, но скрыто.так что с этим сказал и строить на и по вы можете установить
titleForHeaderInSection:к нулю для разделов без строк в нем, как так:- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { if ([tableView.dataSource tableView:tableView numberOfRowsInSection:section] == 0) { return nil; } else { // return your normal return } }
в 2015 году с помощью iOS 8 и Xcode 6 для меня работало следующее:
/* Return the title for each section if and only if the row count for each section is not 0. */ -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{ if ([tableView.dataSource tableView:tableView numberOfRowsInSection:section] == 0) { return nil; }else{ // here you want to return the title or whatever string you want to return for the section you want to display return (SomeObject*)someobjectArray[section].title; } }
это, кажется, правильный путь, он будет анимировать правильно и работает чисто... как и предполагалось Apple...
предоставьте соответствующую информацию делегату tableView
когда нет элементов в разделе, верните 0.0 f в:
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section..Также Верните ноль для:
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)sectionсделайте соответствующее удаление данных для tableView
- вызов
[tableView beginUpdates];- удаление элементов из источника данных, отслеживание о том, где были удалены элементы..
- вызов
deleteRowsAtIndexPathsс индексами клеток, которые вы удалили.- если в вашем источнике данных нет элементов (здесь вы получите только заголовок). Звоните
reloadSections:перезагрузить разделе. Это вызовет правильную анимацию и скрыть/слайд / исчезают заголовок.- наконец-то позвонил
[tableView endUpdates];чтобы завершить обновление..
Comments