如何设置特定节标题的背景颜色?

时间:2012-06-18 06:23:05

标签: ios xcode uitableview header

我有一个TableView,其中有10个部分是从plist文件加载的,我有一些开关可以关闭某些部分。我需要为每个部分设置一个特定的背景颜色,事实上可以禁用该部分。

示例:

部分Black我需要设置black background

部分Red我需要设置red background

依旧......

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *tempHeaderView=[[UIView alloc]initWithFrame:CGRectMake(0,0,320,44)];
     tempHeaderView.backgroundColor=[UIColor blackColor];

     [tempHeaderView addSubView: tempHeaderLabel];
     return tempHeaderView;
}

2 个答案:

答案 0 :(得分:3)

NSArrayUIColor个对象保留为您的类的实例变量(作为委托/数据源的视图控制器),假设您将其称为sectionColors。您可以从plist中的值初始化此数组中的颜色,或者对颜色进行硬编码。

然后,使用此代码:

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *tempHeaderView=[[UIView alloc]initWithFrame:CGRectMake(0,0,320,44)];


    // This changed:
    tempHeaderView.backgroundColor = [sectionColors objectAtIndex:section];

    [tempHeaderView addSubView: tempHeaderLabel];

    return tempHeaderView;
    // Use 'return [tempHeaderView autorelease];' in a non-ARC environment
}

这是初始化数组的方法:

// Assuming your table has three sections (indices 0 through 2)

UIColor* colorForSection0 = [UIColor colorwithRed:redValue0 green:greenValue0 blue:blueValue0 alpha:1.0];
// redValue0, etc. are floats between 0.0 and 1.0 that you can read from a .plist
// Alternatively, store them as integers between 0 and 255, and divide them by 255.0 
// and store on CGFloat variables before creating color.

// ...Do the same for the other colors...

// Now that you have the colors, create array and store in ivar 'sectionColors'
sectionColors = [[NSArray alloc] initWithObjects: 
    ColorforSection0, ColorForSection1, colorForSection2, nil];

(上面的代码应该放在表视图数据源的初始化程序中)

答案 1 :(得分:2)

您需要使用传入的部分并将其与plist文件中的某个部分相关联。您可能会加载一个“section”的字典,因为它存在于plist中(可能根据它在数组中的位置与部分相同而加载),然后在if()中使用valueForKey:@“enabled”或类似的检查,并相应地设置你的状态。

相关问题