UITableView - изменить цвет заголовка раздела
Как изменить цвет заголовка раздела в UITableView?
EDIT. Ответ предоставленный DJ-S, должен быть рассмотрен для iOS 6 и выше. Принятый ответ устарел.
Ответы
Ответ 1
Надеюсь, этот метод из протокола UITableViewDelegate
запустит вас:
Objective-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
.
Ответ 2
Это старый вопрос, но я думаю, что ответ должен быть обновлен.
Этот метод не включает определение и создание собственного пользовательского представления. В 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/
Свифт 3/4
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){
view.tintColor = UIColor.red
let header = view as! UITableViewHeaderFooterView
header.textLabel?.textColor = UIColor.white
}
Ответ 3
Здесь, как изменить цвет текста.
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];
Ответ 4
Вы можете сделать это, если хотите заголовок с пользовательским цветом:
[[UITableViewHeaderFooterView appearance] setTintColor:[UIColor redColor]];
Это решение отлично работает с iOS 6.0.
Ответ 5
Следующее решение работает для 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()
}
Ответ 6
Не забудьте добавить этот фрагмент кода от делегата, иначе ваше мнение будет обрезано или появляться за столом в некоторых случаях относительно высоты вашего представления/метки.
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 30;
}
Ответ 7
Если вы не хотите создавать пользовательский вид, вы также можете изменить его цвет (требуется 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;
}
}
Ответ 8
Установка цвета фона в UITableViewHeaderFooterView устарела. Вместо этого используйте contentView.backgroundColor
.
Ответ 9
Вы можете сделать это на main.storyboard примерно через 2 секунды.
- Выбрать представление таблицы
- Перейти к Инспектору атрибутов
- Элемент списка
- Прокрутите вниз, чтобы просмотреть подзаголовок
- Изменить "фон"
![Посмотрите здесь]()
Ответ 10
Установите цвет фона и текста в области сечения: (Благодаря 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]];
}
}
Ответ 11
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)
}
Это отлично сработало для меня; надеюсь, это вам тоже поможет!
Ответ 12
Здесь, как добавить изображение в виде заголовка:
- (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;
}
Ответ 13
Для iOS8 (Beta) и 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
}
( "override" существует, поскольку я использую UITableViewController вместо обычного UIViewController в моем проекте, но это не обязательно для изменения цвета заголовка раздела)
Текст вашего заголовка все равно будет отображаться.
Обратите внимание, что вам нужно будет отрегулировать высоту заголовка раздела.
Удачи.
Ответ 14
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
}
Ответ 15
Я знаю, что он ответил, на всякий случай, в 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
}
Ответ 16
iOS 8 +
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
tableView.tableHeaderView?.backgroundColor = UIColor.blue()
}
Ответ 17
На основе ответа @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
}
Ответ 18
У меня есть проект с использованием статических табличных ячеек, в 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];
Ответ 19
-(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]];
}
}
Ответ 20
Я думаю, что этот код не так уж плох.
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
}
Ответ 21
В 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;
}
Ответ 22
Просто измените цвет слоя в виде заголовка
- (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
}
Ответ 23
Если кому-то нужно быстро, держите заголовок:
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
}
Ответ 24
В моем случае он работал следующим образом:
let headerIdentifier = "HeaderIdentifier"
let header = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: headerIdentifier)
header.contentView.backgroundColor = UIColor.white
Ответ 25
С RubyMotion/RedPotion вставьте это в свой TableScreen:
def tableView(_, willDisplayHeaderView: view, forSection: section)
view.textLabel.textColor = rmq.color.your_text_color
view.contentView.backgroundColor = rmq.color.your_background_color
end
Работает как шарм!
Ответ 26
Я получил сообщение из Xcode через консольный журнал
[TableView] Установка цвета фона на UITableViewHeaderFooterView устарел. Укажите UIView с желаемым цветом фона в backgroundView вместо этого.
Затем я просто создаю новый UIView и кладу его в качестве фона HeaderView.
Нехорошее решение, но это легко, как сказал Xcode.
Ответ 27
Просто установите цвет фона для фона:
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){
let tableHeader = view as! UITableViewHeaderFooterView
tableHeader.backgroundView?.backgroundColor = UIColor.white
}
Ответ 28
Хотя 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
Ответ 29
Используя UIAppearance, вы можете изменить его для всех заголовков в вашем приложении следующим образом:
UITableViewHeaderFooterView.appearance(). BackgroundColor = theme.subViewBackgroundColor
Ответ 30
Swift 4 делает это очень просто. Просто добавьте это в свой класс и установите цвет по мере необходимости.
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.backgroundColor = UIColor(red: 0.094, green: 0.239, blue: 0.424, alpha: 1.0)
}
или если простой цвет
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.backgroundColor = UIColor.white
}