2013-04-24 63 views
0

這是我的問題。我會創建一個自定義單元格而不創建自定義單元格類。 我知道這是可能的。我在storyboard中創建了一個帶有標籤的原型單元格的tableviewcontroller。在attibutes中,我設置了單元名稱「mycell」。而我使用的代碼是:CustomCell without customCell class

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ static NSString *CellIdentifier = @"mycell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) 
    { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];} 
    UILabel *title = (UILabel*) [cell viewWithTag:1]; 
    title.text = @"Hi"; 
    return cell; 
} 

但是當我的應用程序運行時,我只看到一個沒有帶標籤的單元格的空表。

+0

要退的numberOfRows方法的東西嗎? – 2013-04-24 10:55:06

+0

嘗試:cell.title.text = @「Hi」;你確定你想顯示多少行。 – Sovannarith 2013-04-24 10:56:38

+0

可以顯示UITableViewDataSource的代碼嗎? – Sovannarith 2013-04-24 11:01:16

回答

0

您的UILabel標題爲零。首先創建一個UILabel並將其作爲子視圖添加到您的單元格中。爲此,您可以像下面

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *CellIdentifier = @"mycell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 

    UILabel *title = (UILabel*) [cell viewWithTag:1]; 
    if (title == nil) { 
     title = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 15)]; 
     title.tag = 1; 
     [cell.contentView addSubview:title]; 
    } 

    title.text = @"Hi"; 
    return cell; 
} 
+0

謝謝,但是如果我使用這段代碼,我會在代碼中分配一個標籤,並且標籤分配與標籤在故事板中的標籤1之間沒有相關性。 – user2136333 2013-04-24 15:01:40

+0

您在問題中使用了標籤1。你可以改變它以適應你的需求。 – 2013-04-25 06:22:32