2010-03-05 32 views
9

我有一個非常簡單的問題(我希望如此)。如何將UITableview中的部分標題顏色從默認藍色更改爲黑色透明? 在此先感謝。在UITableview中更改節標題的顏色

+1

這是一個類似的問題:http://stackoverflow.com/questions/813068/uitableview-change-section-header -color – nylund 2011-12-01 13:46:39

回答

18

需要實現在的UITableViewDelegate協議這種方法:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 

這裏是到documentation

鏈接...和做這樣的事情(Sub在自己的顏色):

UIView *sectionView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 22)] autorelease]; 
[sectionView setBackgroundColor:[UIColor blackColor]]; 
return sectionView; 

您也可以使用整數部分替代顏色或類似的東西。我認爲這些部分的默認高度是22,但您可以隨心所欲地製作它。這是你的問題的意思嗎?希望這可以幫助。

+0

謝謝,我想在IB中會有某種觸發器切換成黑色。但無論如何,謝謝。 – 2010-03-05 22:20:59

+1

但請緩存這些視圖。 UIKit中存在一個錯誤,當tableView被滾動時會導致請求標題視圖,所以這個方法將在滾動時調用每個像素偏移量。 22px確實是默認的高度。 – Joost 2010-03-05 22:25:13

+1

嗨,我明白這個方法被稱爲滾動發生時......我們如何緩存這個,以保存不必要的意見被創建等..?如果您可以發佈評論或更新您的帖子,這將是非常有用的。謝謝 – Pavan 2012-08-29 14:20:09

0
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
    { 
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,tableView.bounds.size.width, 30)]; 
    if (section == 0) 
    [headerView setBackgroundColor:[UIColor redColor]]; 
    else 
    [headerView setBackgroundColor:[UIColor clearColor]]; 
    return headerView; 
    } 
20

這是一個老問題,但我認爲答案需要更新。

此方法不涉及定義您自己的自定義視圖。
在iOS 6及更高版本中,您可以通過定義代理方法來輕鬆更改背景顏色和文本顏色。

例如:

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

    // Text Color 
    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view; 
    [header.textLabel setTextColor:[UIColor whiteColor]]; 

    // Another way to set the background color 
    // Note: does not preserve gradient effect of original header 
    // header.contentView.backgroundColor = [UIColor blackColor]; 
} 

從我這裏後摘自: https://happyteamlabs.com/blog/ios-how-to-customize-table-view-header-and-footer-colors/