ios - 如何访问 tableView 的标准 viewForHeaderInSection?

标签 ios uitableview

我有一个带有单独部分的索引 UITableView。我想为每个部分的标题 View 使用不同的背景颜色。我知道我可以通过实现 tableView:viewForHeaderInSection: 完全滚动我自己的 View :(例如,参见 question # 2898361 ),但这对我来说似乎是“太多的工作”——标准 View 看起来不错,我只需要改变它的背景颜色。

但是我如何访问这个标准 View 呢?我不能使用 [super tableView:viewForHeaderInSection:] 因为这是实现协议(protocol)的问题而不是继承的问题。还有其他方法可以获得标准 View 吗?

最佳答案

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

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

真的,创建您自己的 header 并不费力。下面是我从我的一个项目中提取的一些代码——它被注释掉了,所以可能无法立即工作——但你可以理解这个想法:

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

一定要

#import <QuartzCore/QuartzCore.h>

顺便说一下...这不应该模仿标准 header 的外观 - 这只是一个示例。但我敢肯定,通过一些试验和错误,您可以更改它以模仿标准的颜色,然后稍微更改颜色。

关于ios - 如何访问 tableView 的标准 viewForHeaderInSection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7392754/

相关文章:

ios - 如何在滚动时使 UIImage 淡入淡出?

ios - 第二个 View 上的 TableView 单元格

ios - Swift - UITableViewCell 中的自定义文本标签

ios - Xamarin.iOS UITableView,如何强制单元格更新?

objective-c - 在 UITableview 上仅重新加载一个 UITableViewCell

ios - iOS 设备重启后继续位置更新

android - iPhone 5 和 5S 媒体查询级联到三星 Galaxy S4

iOS 12 企业应用程序在启动时崩溃

ios - 我如何获得适用于 ios 5 iPhone 应用程序的 UPC 条码扫描仪框架?

iphone - 空的 nsarray 崩溃 uitableview