UITableView - mudam de cor seção de cabeçalho
-
03-07-2019 - |
Pergunta
Como posso alterar a cor de um cabeçalho de seção na UITableView?
Editar : A resposta fornecido pelo DJ-S deve ser considerado para iOS 6 e acima. A resposta aceita é desatualizado.
Solução
Esperamos que este método a partir do protocolo UITableViewDelegate
irá ajudar a começar:
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
}
Atualização de 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
}
Substituir [UIColor redColor]
com qualquer UIColor
você gostaria. Você também pode querer ajustar as dimensões da headerView
.
Outras dicas
Esta é uma questão de idade, mas acho que as necessidades de resposta para ser atualizado.
Este método não envolve definir e criar a sua própria exibição personalizada. No iOS 6 e acima, você pode facilmente mudar a cor de fundo ea cor do texto, definindo a
-(void)tableView:(UITableView *)tableView
willDisplayHeaderView:(UIView *)view
forSection:(NSInteger)section
método secção delegado
Por exemplo:
- (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];
}
Tomado de meu post aqui: https://happyteamlabs.com/ Blog / ios-how personaliza-a-mesa-view-header-e-footer-cores /
Swift 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
}
Veja como alterar a cor do texto.
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];
Você pode fazer isso se você quiser cabeçalho com cor personalizada:
[[UITableViewHeaderFooterView appearance] setTintColor:[UIColor redColor]];
Esta solução funciona muito bem desde iOS 6.0.
A solução seguinte funciona para
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()
}
Não se esqueça de adicionar este pedaço de código do delegado ou sua visão será cortado ou aparecer atrás da mesa, em alguns casos, em relação à altura da sua visão / label.
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 30;
}
Se você não deseja criar uma exibição personalizada, você também pode mudar a cor como este (requer 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;
}
}
Como definir a cor de fundo em UITableViewHeaderFooterView foi preterido. Por favor uso contentView.backgroundColor
vez.
Definir a cor de fundo e texto da área de secção: (graças a William Jockusch
e 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]];
}
}
Swift 4
Para alterar a cor de fundo , cor rótulo de texto e fonte para o cabeçalho ideia de uma seção UITableView, simplesmente substituir willDisplayHeaderView
para a sua mesa vista assim:
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)
}
Isso funcionou perfeitamente para mim; espero que isso não ajuda você também!
Veja como adicionar uma imagem na visualização de cabeçalho:
- (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;
}
Para iOS8 (Beta) e Swift escolher a cor RGB que você quer e tente o seguinte:
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
}
(A "substituição" é lá desde estou usando o UITableViewController em vez de um UIViewController normal em meu projeto, mas Ele'não é obrigatório para mudar a cor do cabeçalho seção)
O texto do seu cabeçalho vai ainda ser visto. Note que você vai precisar de ajustar a altura do cabeçalho seção.
Good Luck.
SWIFT 2
Eu era capaz de mudar com sucesso a cor seção de fundo com um efeito de borrão adicionado (que é muito legal). Para alterar a cor da seção de fundo facilmente:
- Primeiro, vá para Storyboard e selecione a visualização de mesa
- Vá para Atributos Inspector
- item da lista ??li>
- Vá até Ver
- Change "Background"
Então, para efeito de borrão, adicionar código:
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
}
Eu sei que respondeu, apenas no caso, In Swift usar a seguinte
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
}
iOS 8 +
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
tableView.tableHeaderView?.backgroundColor = UIColor.blue()
}
Com base @Dj S resposta, usando Swift 3. Isso funciona muito bem no 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
}
Eu tenho um projeto usando células visualizar a tabela estática, em iOS 7.x. não willDisplayHeaderView não dispara. No entanto, este método funciona ok:
- (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]];
}
}
Eu acho que este código não é tão ruim.
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
}
Em iOS 7.0.4 Criei um cabeçalho personalizado com seu próprio XIB. Nada aqui mencionado antes trabalhou. Tinha que ser a subclasse do UITableViewHeaderFooterView ao trabalho com o dequeueReusableHeaderFooterViewWithIdentifier:
e parece que a classe é muito teimoso em relação à cor de fundo. Então, finalmente, eu adicionei um UIView (você pode fazê-lo também com o código ou IB) com o nome customBackgroudView, e, em seguida, configurá-lo de backgroundColor propriedade. Em layoutSubviews: eu definir o quadro desse objectivo de limites. É trabalhar com iOS 7 e dá sem falhas.
// 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;
}
Apenas alterar a cor da camada da vista de cabeçalho
- (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 }
Se alguém precisa rápida, mantém título:
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
}
No meu caso, ele trabalhou como esta:
let headerIdentifier = "HeaderIdentifier"
let header = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: headerIdentifier)
header.contentView.backgroundColor = UIColor.white
Basta definir a cor de fundo da opinião do fundo:
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){
let tableHeader = view as! UITableViewHeaderFooterView
tableHeader.backgroundView?.backgroundColor = UIColor.white
}
Com RubyMotion / RedPotion, cole isso em seu TableScreen:
def tableView(_, willDisplayHeaderView: view, forSection: section)
view.textLabel.textColor = rmq.color.your_text_color
view.contentView.backgroundColor = rmq.color.your_background_color
end
funciona como um encanto!
Eu tenho mensagem do Xcode através de registro do console
[TableView] Definir a cor do fundo UITableViewHeaderFooterView foi preterido. Por favor, defina um personalizado UIView com a sua cor de fundo desejada ao backgroundView propriedade em vez.
Então eu apenas criar um novo UIView e colocá-lo como pano de fundo de HeaderView. Não uma boa solução, mas fácil como Xcode disse.
Embora func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)
vai funcionar tão bem, você pode conseguir isso sem implementar outro método delegado.
em você func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
método, você pode usar view.contentView.backgroundColor = UIColor.white
vez de view.backgroundView?.backgroundColor = UIColor.white
que não está funcionando. (Eu sei que backgroundView
é opcional, mas mesmo quando ele está lá, isso não é woking sem implementar willDisplayHeaderView
Usando UIAppearance você pode mudá-lo para todos os cabeçalhos no seu aplicativo como este:
UITableViewHeaderFooterView.appearance (). BackgroundColor = theme.subViewBackgroundColor
Swift 4 torna muito fácil. Simplesmente adicione a sua classe e definir a cor conforme necessário.
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)
}
ou se uma cor simples
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.backgroundColor = UIColor.white
}