UITableView-изменить цвет заголовка раздела
Как я могу изменить цвет заголовка раздела в UITableView?
EDIT: The ответ предоставлен DJ-S следует рассмотреть для iOS 6 и выше. Принятый ответ устарел.
28 ответов:
надеюсь этот метод от
UITableViewDelegateпротокол поможет вам начать:Цель-C:
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)] autorelease]; if (section == integerRepresentingYourSectionOfInterest) [headerView setBackgroundColor:[UIColor redColor]]; else [headerView setBackgroundColor:[UIColor clearColor]]; return headerView; }Swift:
func tableView(_ tableView: UITableView!, viewForHeaderInSection section: Int) -> UIView! { let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 30)) if (section == integerRepresentingYourSectionOfInterest) { headerView.backgroundColor = UIColor.redColor() } else { headerView.backgroundColor = UIColor.clearColor() } return headerView }обновленная 2017:
Swift 3:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 30)) if (section == integerRepresentingYourSectionOfInterest) { headerView.backgroundColor = UIColor.red } else { headerView.backgroundColor = UIColor.clear } return headerView }заменить
[UIColor redColor]С какойUIColorвы хотели бы. Вы также можете настроить размерыheaderView.
Это старый вопрос, но я думаю, что ответ должен быть обновлен.
этот метод не включает в себя определение и создание собственного пользовательского представления. В iOS 6 и выше, вы можете легко изменить цвет фона и цвет текста, определив
-(void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)sectionраздел делегат метод
например:
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section { // Background color view.tintColor = [UIColor blackColor]; // Text Color UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view; [header.textLabel setTextColor:[UIColor whiteColor]]; // Another way to set the background color // Note: does not preserve gradient effect of original header // header.contentView.backgroundColor = [UIColor blackColor]; }взято с моего поста здесь: https://happyteamlabs.com/blog/ios-how-to-customize-table-view-header-and-footer-colors/
Swift 3
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){ view.tintColor = UIColor.red let header = view as! UITableViewHeaderFooterView header.textLabel?.textColor = UIColor.white }
вот как изменить цвет текста.
UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(10, 3, tableView.bounds.size.width - 10, 18)] autorelease]; label.text = @"Section Header Text Here"; label.textColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.75]; label.backgroundColor = [UIColor clearColor]; [headerView addSubview:label];
вы можете сделать это, если вы хотите заголовок с пользовательским цветом:
[[UITableViewHeaderFooterView appearance] setTintColor:[UIColor redColor]];Это решение отлично работает с iOS 6.0.
следующее решение работает для Swift 1.2 с iOS 8+
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { // This changes the header background view.tintColor = UIColor.blueColor() // Gets the header view as a UITableViewHeaderFooterView and changes the text colour var headerView: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView headerView.textLabel.textColor = UIColor.redColor() }
Не забудьте добавить этот фрагмент кода из делегата, иначе ваше представление будет отрезано или появится за таблицей в некоторых случаях относительно высоты вашего представления/метки.
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { return 30; }
Если вы не хотите создавать пользовательский вид, вы также можете изменить цвет следующим образом (Требуется iOS 6):
-(void) tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section { if ([view isKindOfClass: [UITableViewHeaderFooterView class]]) { UITableViewHeaderFooterView* castView = (UITableViewHeaderFooterView*) view; UIView* content = castView.contentView; UIColor* color = [UIColor colorWithWhite:0.85 alpha:1.]; // substitute your color here content.backgroundColor = color; } }
установить цвет фона и текста из раздела: (спасибо
William JockuschиDj S)- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section { if ([view isKindOfClass: [UITableViewHeaderFooterView class]]) { UITableViewHeaderFooterView* castView = (UITableViewHeaderFooterView*) view; castView.contentView.backgroundColor = [UIColor grayColor]; [castView.textLabel setTextColor:[UIColor grayColor]]; } }
вот как добавить изображение в виде заголовка:
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)] autorelease]; UIImageView *headerImage = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"top-gery-bar.png"]] autorelease]; headerImage.frame = CGRectMake(0, 0, tableView.bounds.size.width, 30); [headerView addSubview:headerImage]; return headerView; }
для iOS8 (бета) и Swift выберите нужный цвет RGB и попробуйте следующее:
override func tableView(tableView: UITableView!, viewForHeaderInSection section: Int) -> UIView! { var header :UITableViewHeaderFooterView = UITableViewHeaderFooterView() header.contentView.backgroundColor = UIColor(red: 254.0/255.0, green: 190.0/255.0, blue: 127.0/255.0, alpha: 1) return header}
("переопределение" существует с тех пор, как я использую UITableViewController вместо обычного UIViewController в моем проекте, но это не обязательно для изменения цвета заголовка раздела)
текст вашего заголовка все равно будут видны. Обратите внимание, что вам нужно будет настроить высоту заголовка раздела.
Удачи.
SWIFT 2
мне удалось успешно изменить цвет фона раздела с добавлением эффекта размытия (что действительно круто). Легко изменить цвет фона раздела:
- сначала перейдите в раскадровку и выберите вид таблицы
- перейти к инспектору атрибутов
- элемент списка
- прокрутите вниз, чтобы просмотреть
- Изменение "Фон"
затем для эффекта размытия добавьте к код:
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { // This is the blur effect let blurEffect = UIBlurEffect(style: .Light) let blurEffectView = UIVisualEffectView(effect: blurEffect) // Gets the header view as a UITableViewHeaderFooterView and changes the text colour and adds above blur effect let headerView: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView headerView.textLabel!.textColor = UIColor.darkGrayColor() headerView.textLabel!.font = UIFont(name: "HelveticaNeue-Light", size: 13) headerView.tintColor = .groupTableViewBackgroundColor() headerView.backgroundView = blurEffectView }
Я знаю его ответ, на всякий случай, в Swift используйте следующее
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let tableViewWidth = self.tableView.bounds let headerView = UIView(frame: CGRectMake(0, 0, tableViewWidth.size.width, self.tableView.sectionHeaderHeight)) headerView.backgroundColor = UIColor.greenColor() return headerView }
Swift 4
изменить цвет фона, цвет текстовой метки и шрифт для представления заголовка раздела UITableView просто переопределите
willDisplayHeaderViewдля просмотра таблицы вот так:override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { let header = view as! UITableViewHeaderFooterView header.backgroundView?.backgroundColor = .white header.textLabel?.textColor = .black header.textLabel?.font = UIFont(name: "Helvetica-Bold", size: 14) }это отлично работало для меня; надеюсь, что это поможет вам тоже!
iOS 8+
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { tableView.tableHeaderView?.backgroundColor = UIColor.blue() }
на основе ответа @Dj S, используя Swift 3. Это отлично работает на iOS 10.
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { // Background color view.tintColor = UIColor.black // Text Color let headerView = view as! UITableViewHeaderFooterView headerView.textLabel?.textColor = UIColor.white }
У меня есть проект, использующий статические ячейки табличного представления, в iOS 7.x. willDisplayHeaderView не срабатывает. Однако этот метод работает нормально:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { NSLog(@"%s", __FUNCTION__); CGRect headerFrame = CGRectMake(x, y, w, h); UIView *headerView = [[UIView alloc] initWithFrame:headerFrame]; headerView.backgroundColor = [UIColor blackColor];
-(void) tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section { if ([view isKindOfClass: [UITableViewHeaderFooterView class]]) { UITableViewHeaderFooterView *castView = (UITableViewHeaderFooterView *) view; UIView *content = castView.contentView; UIColor *color = [UIColor whiteColor]; // substitute your color here content.backgroundColor = color; [castView.textLabel setTextColor:[UIColor blackColor]]; } }
Я думаю, что этот код не так уж и плохо.
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier(MyHeaderView.reuseIdentifier) as MyHeaderView let backgroundView = UIView() backgroundView.backgroundColor = UIColor.whiteColor() headerView.backgroundView = backgroundView headerView.textLabel.text = "hello" return headerView }
в iOS 7.0.4 я создал пользовательский заголовок с собственным XIB. Ничего не упоминалось здесь раньше. Это должен был быть подкласс UITableViewHeaderFooterView для работы с
dequeueReusableHeaderFooterViewWithIdentifier:и кажется, что класс очень упрям по поводу цвета фона. Поэтому, наконец, я добавил UIView (вы можете сделать это либо с кодом, либо с IB) с именем customBackgroudView, а затем установил его свойство backgroundColor. В layoutSubviews: я установил рамку этого представления в границы. Он работает с iOS 7 и не дает никаких сбоев.// in MyTableHeaderView.xib drop an UIView at top of the first child of the owner // first child becomes contentView // in MyTableHeaderView.h @property (nonatomic, weak) IBOutlet UIView * customBackgroundView; // in MyTableHeaderView.m -(void)layoutSubviews; { [super layoutSubviews]; self.customBackgroundView.frame = self.bounds; } // if you don't have XIB / use IB, put in the initializer: -(id)initWithReuseIdentifier:(NSString *)reuseIdentifier { ... UIView * customBackgroundView = [[UIView alloc] init]; [self.contentView addSubview:customBackgroundView]; _customBackgroundView = customBackgroundView; ... } // in MyTableViewController.m -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { MyTableHeaderView * header = [self.tableView dequeueReusableHeaderFooterViewWithIdentifier:@"MyTableHeaderView"]; header.customBackgroundView.backgroundColor = [UIColor redColor]; return header; }
просто измените цвет слоя вида заголовка
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)] autorelease]; headerView.layer.backgroundColor = [UIColor clearColor].CGColor }
Если кому-то нужен swift, сохраняет название:
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = UIView(frame: CGRect(x: 0,y: 0,width: self.tableView.frame.width, height: 30)) view.backgroundColor = UIColor.redColor() let label = UILabel(frame: CGRect(x: 15,y: 5,width: 200,height: 25)) label.text = self.tableView(tableView, titleForHeaderInSection: section) view.addSubview(label) return view }
в моем случае это происходило так:
let headerIdentifier = "HeaderIdentifier" let header = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: headerIdentifier) header.contentView.backgroundColor = UIColor.white
С RubyMotion / RedPotion, вставьте это в вашем рабочем столе:
def tableView(_, willDisplayHeaderView: view, forSection: section) view.textLabel.textColor = rmq.color.your_text_color view.contentView.backgroundColor = rmq.color.your_background_color endработает как шарм!
Я получил сообщение от Xcode через журнал консоли
[TableView] установка цвета фона на Uitableviewheaderfooterview является устаревшим. Пожалуйста, установите обычай UIView с желаемым цветом фона для backgroundView собственность вместо этого.
затем я просто создаю новый UIView и кладу его в качестве фона HeaderView. Не очень хорошее решение, но это легко, как сказал Xcode.
хотя
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)также будет работать, вы можете достичь этого без реализации другого метода делегата. в тебеfunc tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?метод, вы можете использоватьview.contentView.backgroundColor = UIColor.whiteвместоview.backgroundView?.backgroundColor = UIColor.whiteкоторый не работает. (Я знаю, чтоbackgroundViewявляется необязательным, но даже когда он есть, это не Уокинг без реализацииwillDisplayHeaderView
используя UIAppearance вы можете изменить его для всех заголовков в вашем приложении следующим образом:
UITableViewHeaderFooterView.внешний вид.)(свойство backgroundColor = тема.subViewBackgroundColor

Comments