2012-04-16 68 views
1

我已將此代碼添加到我的UITableViewController以返回灰色標題部分。UITableview部分標題不顯示文字

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

但是現在在做這件事,我看不到標題字符...我需要添加這個作爲子視圖嗎?還是有另一種做事的方式?

我有這些方法將標題和標題文本添加到UITablView,但是當我使用上述方法時,我不能再看到它們。

// Section headers 
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{  
    return [sectionLetterArray objectAtIndex:section]; 
} 

// Section header titles 
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView 
{ 
    return sectionLetterArray; 
} 

回答

6

如果你創建自己的tableView:viewForHeaderInSection,你必須創建的UILabel或什麼的,然後在文本填寫自己,如:

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
{ 
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)]; 
    [headerView setBackgroundColor:[UIColor grayColor]]; 

    // Add the label 
    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(kSectionTitleLeftMargin, 
                    kSectionTitleTopMargin, 
                    tableView.bounds.size.width - kSectionTitleLeftMargin - kSectionTitleRightMargin, 
                    30.0 - kSectionTitleTopMargin - kSectionTitleBottomMargin)]; 

    // do whatever headerLabel configuration you want here 

    headerLabel.text = [self tableView:tableView titleForHeaderInSection:section]; 
    [headerView addSubview:headerLabel]; 

    // Return the headerView 
    return headerView; 
} 

顯然,改變headerLabel被設置任何你想要的,但關鍵的回家信息是,如果您創建自己的視圖,則必須創建標籤並自行填寫文本。

+0

這是正確的答案。以防萬一你不清楚你是否調用viewForHeaderInSection它會覆蓋titleForHeaderInSection。這就是爲什麼即使你認爲你正在設置它,文本也不會顯示。 – clarky 2012-04-16 03:57:22

+0

對於最近的回覆感到抱歉,我正在研究一個我發現的錯誤,它使我精神緊張,所以我解決了它......只是。大聲笑反正我得到這個錯誤使用未聲明的標識符'kSectionTitleLeftMargin' – 2012-04-16 04:34:45

+0

那麼,你必須決定你如何個人希望你的標籤定位在你的標題。根據所需的外觀和感覺適當定義這四個邊界常數。從零開始,開始縮進你的內容。順便說一句,我不會使用30的靜態高度,而是以編程方式確定高度,但我不想在這裏得到太大的影響...... – Rob 2012-04-16 04:43:59

1

當你實現一個方法,默認視圖,完全與標籤,是由什麼你回來更換,所以這是你的任務是用任何你想要的文本添加了標籤。

+0

我編輯了我的問題以顯示添加文本的方法。 – 2012-04-16 01:00:13