保持一個NSArray
UIColor
對象作爲你的類的一個實例變量(視圖控制器充當委託/數據源),假設你稱之爲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];
(上面的代碼應該去表視圖數據源的初始化中)
除非您使用ARC(自動引用計數),否則您的代碼正在泄漏tempHeaderView。在這種情況下查看我的答案。 –
我使用ARC ...謝謝! –
使用ARC的+1 :) –