简体   繁体   English

如何在UITableView中更改基于索引的部分常用颜色

[英]How to change index based section common color in UITableView

Normally my screen display is like this: 通常我的屏幕显示是这样的:

在此处输入图片说明

When I use this code 当我使用此代码

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)];

    [headerView setBackgroundColor:[UIColor whiteColor]];

    return headerView;
}

my output is like this: 我的输出是这样的:

在此处输入图片说明

My section index text is not visible. 我的部分索引文本不可见。 I know that the section header view add my custom view. 我知道部分标题视图会添加我的自定义视图。 I want to change section header color and also display index text. 我想更改节标题颜色并显示索引文本。

@Khawar answer i get this output @Khawar答案我得到这个输出

在此处输入图片说明

Try to set the height for UITableView header. 尝试设置UITableView标头的高度。

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

If you only need to change the background color of section header while displaying section title, you don't need to create custom view for that. 如果在显示节标题时仅需要更改节标题的背景颜色,则无需为此创建自定义视图。 Custom view would overwrite your default header and your title would not be shown, unless you add custom UILabel in your custom view. 除非您在自定义视图中添加自定义UILabel,否则自定义视图将覆盖默认标题,并且标题将不会显示。 Just use following UITableView delegate to change background color. 只需使用以下UITableView委托即可更改背景颜色。

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    view.tintColor = [UIColor redColor];
}

See results before and after. 查看之前和之后的结果。

----------------Before------------------ - - - - - - - - 之前 - - - - - - - - -

在此处输入图片说明

----------------After------------------ - - - - - - - - 后 - - - - - - - - -

在此处输入图片说明

Hope this fixes the issue. 希望这可以解决问题。

this is work 100% and you can change your index or header text color 这是100%的工作,您可以更改索引或标题文本的颜色

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    view.tintColor = [UIColor blueColor];

    // if you have index/header text in your tableview change your index text color 
    UITableViewHeaderFooterView *headerIndexText = (UITableViewHeaderFooterView *)view;
    [headerIndexText.textLabel setTextColor:[UIColor blackColor]];

}

output: 输出:

在此处输入图片说明

You have to give title for section... Or you can use this method.. 您必须为该部分提供标题...或者您可以使用此方法。

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UILabel *headerView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)];
   [headerView setBackgroundColor:[UIColor colorWithWhite:0 alpha:0.5]];
    headerView.text = [self tableView:tableView titleForHeaderInSection:section];
    return headerView;
}

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

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