如何访问tableView的标准viewForHeaderInSection?

Tho*_*ten 6 uitableview ios

我有一个索引的UITableView与各个部分.我想为每个部分中的标题视图使用不同的背景颜色.我知道我可以通过实现tableView来完成自己的视图:viewForHeaderInSection :(例如,参见问题#2898361),但这对我来说似乎"太多了" - 标准视图看起来很好,我只需要更改它的背景颜色.

但是如何访问此标准视图?我无法使用,[super tableView:viewForHeaderInSection:]因为这是一个实现协议而不是继承问题的问题.我可以通过其他方式获得标准视图吗?

ban*_*isa 13

我几乎可以肯定你不能轻易做到这一点.我最近在我的开发帐户上使用了我的技术支持请求之一,询问有关更改UITableView部分的背景和边框的问题.这位苹果工程师告诉我,这真的不是一件容易的事,即使你成功了,也可能会影响性能.他还向我指出了cocoawithlove和一篇关于编辑uitableviews的文章:

http://cocoawithlove.com/2009/08/adding-shadow-effects-to-uitableview.html

真的,创建自己的标题并不是那么费力.下面是我从我的一个项目中提取的一些代码 - 它被注释掉了,所以可能不会马上工作 - 但你可以得到这个想法:

 - (CAGradientLayer *) greyGradient {
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.startPoint = CGPointMake(0.5, 0.0);
    gradient.endPoint = CGPointMake(0.5, 1.0);

    UIColor *color1 = [UIColor colorWithRed:255.0f/255.0f green:255.0f/255.0f blue:255.0f/255.0f alpha:1.0];
    UIColor *color2 = [UIColor colorWithRed:240.0f/255.0f green:240.0f/255.0f blue:240.0f/255.0f alpha:1.0];

    [gradient setColors:[NSArray arrayWithObjects:(id)color1.CGColor, (id)color2.CGColor, nil]];
    return gradient;
}

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    CGFloat width = CGRectGetWidth(tableView.bounds); 
    CGFloat height = [self tableView:tableView heightForHeaderInSection:section];
    UIView *container = [[[UIView alloc] initWithFrame:CGRectMake(0,0,width,height)] autorelease];
    container.layer.borderColor = [UIColor grayColor].CGColor;
    container.layer.borderWidth = 1.0f;
    CAGradientLayer *gradient = [self greyGradient];
    gradient.frame = container.bounds;
    [container.layer addSublayer:gradient];

    UILabel *headerLabel = [[[UILabel alloc] initWithFrame:CGRectMake(12,0,width,height)] autorelease];
    headerLabel.backgroundColor = [UIColor clearColor];
    headerLabel.font= [UIFont boldSystemFontOfSize:19.0f];
    headerLabel.shadowOffset = CGSizeMake(1, 1);
    headerLabel.textColor = [UIColor whiteColor];
    headerLabel.shadowColor = [UIColor darkGrayColor];
    NSString *title = [self tableView:tableView titleForHeaderInSection:section];
    headerLabel.text = title;
    return container;
}
Run Code Online (Sandbox Code Playgroud)

确保

#import <QuartzCore/QuartzCore.h>
Run Code Online (Sandbox Code Playgroud)

顺便说一句......这不应该模仿标准标题的外观 - 它只是一个例子.但我确定通过一些试验和错误你可以改变它来模仿标准的,然后稍微改变颜色.


Phi*_*vin 5

虽然其他答案正确指出您无法访问默认视图以对其进行简单修改,但如果您没有为特定节标题自定义,则可以返回nil,tableView:viewForHeaderInSection:并且表视图将使用默认视图.

如果您只需要自定义一些标题,这将非常有用.

无论出于何种原因,这都没有记录.