Как изменить стиль шрифта и цвет фона в методе titleForHeaderInSection
после длительного чтения и проверки кода, я горжусь тем, что у меня есть собственное табличное представление с разделами и заголовками разделов, все из которых заполнены основными объектами данных. Теперь мне нужно будет настроить заголовок раздела и цвет фона. Я видел это, но в методе viewForHeaderInSection
. Невозможно ли внутри метода titleForHeaderInSection
?
Здесь у вас есть мой метод:
-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
id <NSFetchedResultsSectionInfo> theSection = [[self.fetchedResultsController sections]objectAtIndex:section];
NSString *sectionname = [theSection name];
if ([sectionname isEqualToString:@"text 1"]){
return @"Today";
}
else if ([sectionname isEqualToString:@"text 2"]){
return @"Tomorrow";
}
if ([[self.fetchedResultsController sections]count]>0){
id<NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections]objectAtIndex:section];
return [sectionInfo name];
}
else{
return nil;
}
}
Ответы
Ответ 1
Вот пример, который использует ваш существующий код для установки текста заголовка, но позволяет вам использовать UITableViewHeaderFooterView для настройки внешнего вида:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
static NSString *header = @"customHeader";
UITableViewHeaderFooterView *vHeader;
vHeader = [tableView dequeueReusableHeaderFooterViewWithIdentifier:header];
if (!vHeader) {
vHeader = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:header];
vHeader.textLabel.backgroundColor = [UIColor redColor];
}
vHeader.textLabel.text = [self tableView:tableView titleForHeaderInSection:section];
return vHeader;
}
Если вы хотите, вы можете даже подклассифицировать UITableViewHeaderFooterView
так же, как и подкласс UITableViewCell
, чтобы еще больше настроить внешний вид.
Ответ 2
простой и оптимизированный
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
// Background color
view.tintColor = [UIColor whiteColor];//[UIColor colorWithRed:77.0/255.0 green:162.0/255.0 blue:217.0/255.0 alpha:1.0];
// Text Color
UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
[header.textLabel setTextColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"tableSection"]]];
}
Ответ 3
Быстрая реализация ответа @codercat:
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.tintColor = UIColor(red: 0.967, green: 0.985, blue: 0.998, alpha: 1) // this example is a light blue, but of course it also works with UIColor.lightGrayColor()
var header : UITableViewHeaderFooterView = view as UITableViewHeaderFooterView
header.textLabel.textColor = UIColor.redColor()
}
Ответ 4
Создайте пользовательский заголовок с помощью:
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *viewHeader = [UIView.alloc initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 28)];
UILabel *lblTitle =[UILabel.alloc initWithFrame:CGRectMake(6, 3, 136, 21)];
[lblTitle setFont:[UIFont fontWithName:@"HelveticaNeue" size:13]]; //Font style
[lblTitle setTextColor:[UIColor blackColor]];
[lblTitle setTextAlignment:NSTextAlignmentLeft];
[lblTitle setBackgroundColor:[UIColor clearColor]]; //Background
[viewHeader addSubview:lblTitle];
return viewHeader;
}
Дайте этому ярлыку любой текст; Я предлагаю сделать отдельный NSArray для заголовков заголовков.
Ответ 5
Я думаю, что в titleForHeaderInSection
вы не можете изменять свойства сечения.
Добавьте в проект viewForHeaderInSection
, а затем добавьте пользовательский вид с меткой на нем, например.
см. этот подсказку:
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 0)] autorelease];
UILabel *label = [[[UILabel alloc] init] autorelease];
label.frame = CGRectMake(0, 0,300, TABLE_HEADER_HEIGHT);
label.backgroundColor = [UIColor clearColor];
label.textColor = TABLE_HEADER_TITLE_COLOR;
label.font = [UIFont fontWithName:FONT_NAME size:14.f];
label.text = [self tableView:tableView titleForHeaderInSection:section];
if (section == 3) {
[headerView setBackgroundColor:[UIColor whiteColor]];
} else {
[headerView setBackgroundColor:[UIColor redColor]];
}
[headerView addSubview:label];
return headerView;
}
Вы можете установить заголовок для метки в соответствии с номером секции.