UITableView с фиксированными заголовками разделов
здоровается,
Я читаю, что поведение по умолчанию UITableView - это закрепление строк заголовка раздела В верхней части таблицы при прокрутке разделов до тех пор, пока следующий раздел не вытеснит строку раздела previos из поля зрения.
у меня есть UITableView внутри UIViewController и это, кажется, не так.
это просто поведение по умолчанию для UITableViewController?
вот немного упрощенный код, основанный на том, что у меня есть.
Я покажу UIController интерфейс и каждого метод представления таблицы, который я реализовал для создания представления таблицы.
У меня есть вспомогательный класс источника данных, который помогает мне индексировать объекты для использования в таблице.
@interface MyUIViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, readonly) UITableView *myTableView;
@property (nonatomic, readonly) MyCustomHelperDataSource *helperDataSource;
@end
//when section data is set, get details for each section and reload table on success
- (void)setSectionData:(NSArray *)sections {
super.sectionData = sections; //this array drives the sections
//get additional data for section details
[[RestKitService sharedClient] getSectionDetailsForSection:someId
success:^(RKObjectRequestOperation *operation, RKMappingResult *details) {
NSLog(@"Got section details data");
_helperDataSource = [[MyCustomHelperDataSource alloc] initWithSections:sections andDetails:details.array];
[myTableView reloadData];
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(@"Failed getting section details");
}];
}
#pragma mark <UITableViewDataSource, UITableViewDelegate>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if (!_helperDataSource) return 0;
return [_helperDataSource countSectionsWithDetails]; //number of section that have details rows, ignore any empty sections
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//get the section object for the current section int
SectionObject *section = [_helperDataSource sectionObjectForSection:section];
//return the number of details rows for the section object at this section
return [_helperDataSource countOfSectionDetails:section.sectionId];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell * cell;
NSString *CellIdentifier = @"SectionDetailCell";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
cell.textLabel.font = [UIFont systemFontOfSize:12.0f];
}
//get the detail object for this section
SectionObject *section = [_helperDataSource sectionObjectForSection:indexPath.section];
NSArray* detailsForSection = [_helperDataSource detailsForSection:section.sectionId] ;
SectionDetail *sd = (SectionDetail*)[detailsForSection objectAtIndex:indexPath.row];
cell.textLabel.text = sd.displayText;
cell.detailTextLabel.text = sd.subText;
cell.detailTextLabel.textColor = [UIColor blueTextColor];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 50.0f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 30.0f;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger) section {
//get the section object for the current section
SectionObject *section = [_helperDataSource sectionObjectForSection:section];
NSString *title = @"%@ (%d)";
return [NSString stringWithFormat:title, section.name, [_helperDataSource countOfSectionDetails:section.sectionId]];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 260, 0)];
header.autoresizingMask = UIViewAutoresizingFlexibleWidth;
header.backgroundColor = [UIColor darkBackgroundColor];
SSLabel *label = [[SSLabel alloc] initWithFrame:CGRectMake(3, 3, 260, 24)];
label.font = [UIFont boldSystemFontOfSize:10.0f];
label.verticalTextAlignment = SSLabelVerticalTextAlignmentMiddle;
label.backgroundColor = [UIColor clearColor];
label.text = [self tableView:tableView titleForHeaderInSection:section];
label.textColor = [UIColor whiteColor];
label.shadowColor = [UIColor darkGrayColor];
label.shadowOffset = CGSizeMake(1.0, 1.0);
[header addSubview:label];
return header;
}
6 ответов:
заголовки остаются фиксированными только тогда, когда
UITableViewStyleсвойство таблицы имеет значениеUITableViewStylePlain. Если он установлен вUITableViewStyleGrouped, заголовки будут прокручиваться вместе с ячейками.
вы также можете установить отскакивает свойство TableView для того, чтобы не. Это сохранит заголовки разделов неплавающими / статическими, но тогда вы также потеряете свойство bounce tableview.
Swift 3.0
создать ViewController С UITableViewDelegate и UITableViewDataSource протоколов. Затем создайте tableView внутри него, объявив его стиль UITableViewStyle.сгруппированы. Это исправит заголовки.
lazy var tableView: UITableView = { let view = UITableView(frame: UIScreen.main.bounds, style: UITableViewStyle.grouped) view.delegate = self view.dataSource = self view.separatorStyle = .none return view }()
измените свой стиль TableView:
self.tableview = [[UITableView alloc] initwithFrame: кадр стиль:UITableViewStyleGrouped];
согласно документации apple для UITableView:
UITableViewStylePlain-простой вид таблицы. Любые заголовки разделов или нижние колонтитулы отображаются как встроенные разделители и плавают, когда таблица вид прокручивается.
UITableViewStyleGrouped-табличное представление, секции которого присутствуют отчетливый группы строк. Верхние и нижние колонтитулы раздела не плавают.
надеюсь, что это небольшое изменение поможет вам ..
теперь ваш tableview выглядит как простой стиль таблицы, но не плавает buz установка стиля таблицы установить в группу.
[_tableView setBackgroundView:nil]; _tableView.backgroundColor = [UIColor whiteColor];
чтобы сделать заголовок разделов UITableView не липким или липким:
измените стиль представления таблицы - сделайте его сгруппированным для не липкого и сделайте его простым для липких заголовков разделов-не забывайте: вы можете сделать это из раскадровки без написания кода. (нажмите на свой вид таблицы и измените его стиль с правой стороны / меню компонентов)
Если у вас есть дополнительные компоненты, такие как пользовательские представления и т. д. пожалуйста, проверьте поля представления таблицы, чтобы создайте соответствующий дизайн. (например, высота заголовка для разделов и высота ячейки в пути индекса, разделы)
Comments