2011-05-17 69 views
0

我有UITableViewController其中包含項目列表。現在,我希望列表在視圖出現後自動滾動到一個項目(索引= bestOne)。同時,我希望將該物品塗成紅色並標記爲Marked以編程方式滾動並在運行時着色UITableViewCell

我的代碼粗略地實現了我想要的。但是,我實際上看到不止一個紅色物品迭代:每10個物品都有一個紅色物品。

我對iphone開發相當陌生,我認爲它可能與可重用的單元格有關。但我不確定爲什麼。任何人都可以提出一種解決這個問題的方法嗎?提前致謝。

(void)viewDidAppear:(BOOL)animated 
{ 
    if (self.bestOne != -1) 
    { 
     NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.bestOne inSection:0]; 
     [self.tableView scrollToRowAtIndexPath: atScrollPosition: animated:YES]; 
    } 
} 


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 

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

    cell.textLabel.text = [self.array objectAtIndex:indexPath.row]; 
    if (indexPath.row == self.bestOne) 
    { 
     cell.detailTextLabel.text = @"Marked"; 
     cell.textLabel.textColor = [UIColor redColor]; 
    } 
    return cell; 
} 

回答

1

您對可重複使用的細胞部分是正確的。

你的代碼應該是這樣的 -

cell.textLabel.text = [self.array objectAtIndex:indexPath.row]; 
if (indexPath.row == self.bestOne) 
{ 
    cell.detailTextLabel.text = @"Marked"; 
    cell.textLabel.textColor = [UIColor redColor]; 
} 
else 
{ 
    cell.detailTextLabel.text = @""; 
} 

在重用,你會得到你以前設置的確切細胞。雖然其他細胞是不可區分的,但標記的細胞以其專門設置的detailTextLabel突出。您需要重置它,然後才能將其用作未標記的單元格。

+0

不要忘記重置'textLabel.textColor'! – thelaws 2011-05-17 04:33:46

+0

它的工作原理。我沒有想到它會那麼簡單。謝謝。 – Zeiga 2011-05-17 04:36:02

+0

@Zeiga,@thelaws是對的。我沒有添加'cell.textLabel.textColor = [UIColor blackColor];',因爲我誤以爲它是'detailTextLabel'。你也應該添加它。 – 2011-05-17 04:41:26

0

您看起來像是在正確的軌道上出現顏色問題,如果您沒有專門調用[tableView reloadData]或重新加載舊的紅色單元格,您可能會累積紅色的文本單元格,一張大桌子。你的滾動看起來不錯,不知道爲什麼不行。