2011-07-30 137 views
0

我想知道如何根據單元格的文本內容在單元格中顯示特定類型的圖像。例如,從我一起工作的指南書,指導這個方法可以讓我的前3個單元格顯示明星形象:基於單元格數據的iPhone表格視圖單元格樣式

- (UITableViewCell *)tableView:(UITableView *)tableView 
     cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: 
          SimpleTableIdentifier]; 
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] 
       initWithStyle:UITableViewCellStyleDefault 
       reuseIdentifier:SimpleTableIdentifier] autorelease]; 
    } 

    NSUInteger row = [indexPath row]; 
    if (row < 3) { 
     UIImage *image = [UIImage imageNamed:@"star.png"]; 
     cell.imageView.image = image; 
    } 


    cell.textLabel.text = [listData objectAtIndex:row]; 
    cell.textLabel.font = [UIFont boldSystemFontOfSize:15]; 


    return cell; 
} 

有什麼辦法,我可以在這裏得到實際的單元格內容?所以例如,如果單元格包含文字'bob',我可以顯示不同的圖像而不是明星?

回答

2

那麼它好像你可以看看你的listData對象,並決定在那裏。所以你可以嘗試這樣的事情

- (UITableViewCell *)tableView:(UITableView *)tableView 
     cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: 
          SimpleTableIdentifier]; 
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] 
       initWithStyle:UITableViewCellStyleDefault 
       reuseIdentifier:SimpleTableIdentifier] autorelease]; 
    } 

    NSUInteger row = [indexPath row]; 
    if ([[listData objectAtIndex:row] isEqualToString:@"bob"]) { 
     UIImage *image = [UIImage imageNamed:@"bob.png"]; 
     cell.imageView.image = image; 
    } 
    else if (row < 3) { 
     UIImage *image = [UIImage imageNamed:@"star.png"]; 
     cell.imageView.image = image; 
    } 


    cell.textLabel.text = [listData objectAtIndex:row]; 
    cell.textLabel.font = [UIFont boldSystemFontOfSize:15]; 


    return cell; 
} 
+0

謝謝,appologies,因爲我是一個新的iOS ...我完全忽略了listData objectAtIndex:row – Hoofamon

0

也許你應該設置一個字典,其中包含人的名字作爲字典和圖像名稱的關鍵字作爲值。然後,您可以獲取單元格的文本並將其用作字典的查找。

0

在設置文本:

if([cell.textLabel.text rangeOfString:@"bob"].location != NSNotFound) { 
    UIImage *image = [UIImage imageNamed:@"bob.png"]; 
    cell.imageView.image = image; 
} 
else { 
    UIImage *image = [UIImage imageNamed:@"star.png"]; 
    cell.imageView.image = image; 
} 
相關問題