简体   繁体   English

UITableView - 更改部分标题颜色

[英]UITableView - change section header color

How can I change color of a section header in UITableView?如何更改 UITableView 中节标题的颜色?

EDIT : The answer provided by DJ-S should be considered for iOS 6 and above.编辑:应考虑DJ-S 提供答案适用于 iOS 6 及更高版本。 The accepted answer is out of date.接受的答案已过时。

This is an old question, but I think the answer needs to be updated.这是一个老问题,但我认为答案需要更新。

This method does not involve defining and creating your own custom view.此方法不涉及定义和创建您自己的自定义视图。 In iOS 6 and up, you can easily change the background color and the text color by defining the在 iOS 6 及更高版本中,您可以通过定义

-(void)tableView:(UITableView *)tableView 
    willDisplayHeaderView:(UIView *)view 
    forSection:(NSInteger)section

section delegate method节委托方法

For example:例如:

- (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];
}

Taken from my post here: https://happyteamlabs.com/blog/ios-how-to-customize-table-view-header-and-footer-colors/摘自我在这里的帖子: https : //happyteamlabs.com/blog/ios-how-to-customize-table-view-header-and-footer-colors/

Swift 3 / 4斯威夫特 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
}

Hopefully this method from the UITableViewDelegate protocol will get you started:希望UITableViewDelegate协议中的这个方法能让你开始:

Objective-C:目标-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
}

Updated 2017: 2017 年更新:

Swift 3:斯威夫特 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
    }

Replace [UIColor redColor] with whichever UIColor you would like.[UIColor redColor]替换为您想要的任何UIColor You may also wish to adjust the dimensions of headerView .您可能还希望调整headerView的尺寸。

Here's how to change the text color.以下是更改文本颜色的方法。

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];

You can do this if you want header with custom color.如果您想要带有自定义颜色的标题,则可以执行此操作。 This solution works great since iOS 6.0.自 iOS 6.0 以来,此解决方案效果很好。

Objective C:目标 C:

[[UITableViewHeaderFooterView appearance] setTintColor:[UIColor redColor]];

Swift:迅速:

UITableViewHeaderFooterView.appearance().tintColor = .white

The following solution works for Swift 1.2 with iOS 8+以下解决方案适用于iOS 8+ 的 Swift 1.2

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()

}

Setting the background color on UITableViewHeaderFooterView has been deprecated.不推荐在 UITableViewHeaderFooterView 上设置背景颜色。 Please use contentView.backgroundColor instead.请改用contentView.backgroundColor

You can do it on main.storyboard in about 2 seconds.您可以在大约 2 秒内在 main.storyboard 上完成。

  1. Select Table View选择表格视图
  2. Go to Attributes Inspector转到属性检查器
  3. List item项目清单
  4. Scroll down to View subheading向下滚动到查看副标题
  5. Change "background"换背景”

看看这里

Don't forget to add this piece of code from the delegate or your view will be cut off or appear behind the table in some cases, relative to the height of your view/label.不要忘记从委托中添加这段代码,否则在某些情况下,相对于视图/标签的高度,您的视图将被切断或出现在表格后面。

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

If you don't want to create a custom view, you can also change the color like this (requires iOS 6):如果不想创建自定义视图,也可以像这样更改颜色(需要 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;
    }
}

Set the background and text color of section area: (Thanks to William Jockusch and Dj S )设置部分区域的背景和文本颜色:(感谢William JockuschDj 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斯威夫特 4

To change the background color , text label color and font for the Header View of a UITableView Section, simply override willDisplayHeaderView for your table view like so:要更改 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)
} 

This worked perfectly for me;这对我来说非常有效; hope it does help you too!希望它也能帮到你!

Here's how to add an image in header view:以下是在标题视图中添加图像的方法:

- (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;
}

For iOS8 (Beta) and Swift choose the RGB Color you want and try this:对于 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

} }

(The "override" is there since i´m using the UITableViewController instead of a normal UIViewController in my project, but it´s not mandatory for changing the section header color) (“覆盖”是存在的,因为我在我的项目中使用 UITableViewController 而不是普通的 UIViewController,但更改部分标题颜色不是强制性的)

The text of your header will still be seen.仍然会看到标题的文本。 Note that you will need to adjust the section header height.请注意,您需要调整节标题高度。

Good Luck.祝你好运。

For swift 5 +快速 5 +

In willDisplayHeaderView MethodwillDisplayHeaderView方法中

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {

     //For Header Background Color
     view.tintColor = .black

    // For Header Text Color
    let header = view as! UITableViewHeaderFooterView
    header.textLabel?.textColor = .white
}

I hope this helps you :]我希望这可以帮助你 :]

SWIFT 2快速 2

I was able to successfully change the section background color with an added blur effect (which is really cool).我能够通过添加模糊效果成功更改部分背景颜色(这真的很酷)。 To change the background color of section easily:要轻松更改部分的背景颜色:

  1. First go to Storyboard and select the Table View首先转到 Storyboard 并选择 Table View
  2. Go to Attributes Inspector转到属性检查器
  3. List item项目清单
  4. Scroll down to View向下滚动查看
  5. Change "Background"换背景”

Then for blur effect, add to code:然后对于模糊效果,添加到代码中:

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 4 makes it very easy. Swift 4 让它变得非常简单。 Simply add this to your class and set the color as needed.只需将其添加到您的班级并根据需要设置颜色。

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)
    }

or if a simple color或者如果一个简单的颜色

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        view.backgroundColor = UIColor.white
    }

Updated for Swift 5为 Swift 5 更新

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        view.tintColor = UIColor(red: 0.094, green: 0.239, blue: 0.424, alpha: 1.0)
    }

or if a simple color或者如果一个简单的颜色

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        view.tintColor = UIColor.white
    }

I know its answered, just in case, In Swift use the following我知道它的回答,以防万一,在 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
    }

iOS 8+ iOS 8+

func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        tableView.tableHeaderView?.backgroundColor = UIColor.blue()
}

Based on @Dj S answer, using Swift 3. This works great on iOS 10.基于@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
}

For me none of above works after wasting 2 hours what this is the solution.对我来说,在浪费了 2 个小时之后,以上都不起作用,这是解决方案。 In my case it was custom view but I cannot able to change it from storyboard and view's awakeFromNib for some reason.就我而言,它是自定义视图,但由于某种原因,我无法从故事板和视图的awakeFromNib 更改它。

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        let header = view as! UITableViewHeaderFooterView
        header.contentView.backgroundColor = .white
    }

I have a project using static table view cells, in iOS 7.x.我在 iOS 7.x 中有一个使用静态表格视图单元格的项目。 willDisplayHeaderView does not fire. willDisplayHeaderView 不会触发。 However, this method works 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]];
        }
 }

I think this code is not so bad.我认为这段代码还不错。

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
}

In iOS 7.0.4 I created a custom header with it's own XIB.在 iOS 7.0.4 中,我用它自己的 XIB 创建了一个自定义标头。 Nothing mentioned here before worked.这里没有提到工作之前。 It had to be the subclass of the UITableViewHeaderFooterView to work with the dequeueReusableHeaderFooterViewWithIdentifier: and it seems that class is very stubborn regarding the background color.它必须是 UITableViewHeaderFooterView 的子类才能与dequeueReusableHeaderFooterViewWithIdentifier: ,而且该类似乎对背景颜色非常固执。 So finally I added an UIView (you could do it either with code or IB) with name customBackgroudView, and then set it's backgroundColor property.所以最后我添加了一个名为 customBackgroudView 的 UIView(你可以用代码或 IB 来完成),然后设置它的 backgroundColor 属性。 In layoutSubviews: I set that view's frame to bounds.在 layoutSubviews 中:我将该视图的框架设置为边界。 It work with iOS 7 and gives no glitches.它适用于 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;
}

Just change the color of layer of the header view只需更改标题视图图层的颜色

- (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
}

If anyone needs swift, keeps title:如果有人需要快速,请保留标题:

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
}

I got message from Xcode through console log我通过控制台日志从 Xcode 收到消息

[TableView] Setting the background color on UITableViewHeaderFooterView has been deprecated. [TableView] UITableViewHeaderFooterView 背景色设置已弃用。 Please set a custom UIView with your desired background color to the backgroundView property instead.请改为将具有所需背景颜色的自定义 UIView 设置为 backgroundView 属性。

Then I just create a new UIView and lay it as background of HeaderView.然后我只是创建一个新的 UIView 并将其作为 HeaderView 的背景。 Not a good solution but it easy as Xcode said.不是一个好的解决方案,但正如 Xcode 所说的那样简单。

In my case, It worked like this:就我而言,它是这样工作的:

let headerIdentifier = "HeaderIdentifier"
let header = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: headerIdentifier)
header.contentView.backgroundColor = UIColor.white

Just set the background color of the background view:只需设置背景视图的背景颜色:

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){         
  let tableHeader = view as! UITableViewHeaderFooterView        
  tableHeader.backgroundView?.backgroundColor = UIColor.white     
}

How can I change color of a section header in UITableView?如何在UITableView中更改节标题的颜色?

EDIT : The answer provided by DJ-S should be considered for iOS 6 and above.编辑:对于iOS 6及更高版本,应考虑DJ-S提供答案 The accepted answer is out of date.接受的答案已过期。

If you are using a custom header view:如果您使用自定义标题视图:

class YourCustomHeaderFooterView: UITableViewHeaderFooterView { 

override func awakeFromNib() {
    super.awakeFromNib()
    self.contentView.backgroundColor = .white //Or any color you want
}

} }

How can I change color of a section header in UITableView?如何在UITableView中更改节标题的颜色?

EDIT : The answer provided by DJ-S should be considered for iOS 6 and above.编辑:对于iOS 6及更高版本,应考虑DJ-S提供答案 The accepted answer is out of date.接受的答案已过期。

Using UIAppearance you can change it for all headers in your application like this: 使用UIAppearance,您可以为应用程序中的所有标题更改它,如下所示:

UITableViewHeaderFooterView.appearance().backgroundColor = theme.subViewBackgroundColor UITableViewHeaderFooterView.appearance()。backgroundColor = theme.subViewBackgroundColor

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM