2011-06-14 68 views
1

我有一個tableview,我需要每次選擇一行時顯示一個複選標記。 (多選)我的代碼如下。我也能夠取消選擇一行。問題:正在重用多個選擇tableview單元格

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
static NSString *RootViewControllerCell = @"RootViewControllerCell"; 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:RootViewControllerCell]; 

if(nil == cell) 
{ 
    cell = [[[UITableViewCell alloc]initWithFrame:CGRectZero reuseIdentifier:RootViewControllerCell] autorelease]; 

} 
cell.textLabel.font = [UIFont fontWithName:[NSString stringWithFormat:@"HelveticaNeue-Bold"] size:12]; 
textView.textColor = [UIColor colorWithRed:0.281 green:0.731 blue:0.8789 alpha:1]; 
cell.textLabel.text = [optionsArray objectAtIndex:[indexPath row]]; 
if (pathIndex == indexPath) 
{ 
    if (cell.accessoryType == UITableViewCellAccessoryCheckmark) 
    { 
     cell.accessoryType = UITableViewCellAccessoryNone; 
    } 
    else { 
     cell.accessoryType = UITableViewCellAccessoryCheckmark; 
    } 
} 
return cell; 
} 
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
pathIndex = indexPath; 
[surveytableView reloadData]; 
} 

但我有一個單元格被重用的問題。當我選擇一個單元另一個單元其他地方也被選中。只有複選標記(或沒有複選標記)纔會被重用,其他細節(如行標題等)不會被重用。任何解決方案來解決這個提前致謝。

+0

我發現從堆棧溢出回答另一個問題一個解決方案: http://stackoverflow.com/questions/6023883/ uitableview-multiple-checkmark-selection Folllow this above link。似乎現在對我來說工作得很好。 – 2011-06-14 07:33:29

回答

0

在你

if (pathIndex == indexPath) 

你比較指針不是他們的價值觀,嘗試

[pathIndex isEqual:indexPath] 

或使用

- (NSComparisonResult)compare:(NSIndexPath *)otherObject; 

接下來你將值分配給pathIndex沒有保留或複製它像

pathIndex = [indexPath copy]; 

(當然現在因爲你保留的價值,複製,你必須釋放前一個[pathIndex發行]新對象之前;)

最後,沒有多重選擇由您的實現提供,只有單一的選擇。您可以嘗試添加NSIndexPath對象並將其移除到NSMutableArray,然後檢查它們在cellForRowAtIndexPath中的可變數組中是否存在。

0

問題是,如果當前行與pathIndex ....匹配,那麼您只對附件執行某些操作......那麼如果它是一個正常的單元格...?你永遠不會回頭。你想...

cell.accessoryType = UITableViewCellAccessoryNone; 

if ([pathIndex isEqual:indexPath]) 
{ 
    cell.accessoryType = UITableViewCellAccessoryCheckmark; 
} 

在設置任何特定屬性之前重置單元是一種很好的做法。

2

將它添加到cellForRowAtIndexPath

if ([tableView.indexPathsForSelectedRows containsObject:indexPath]) { 
    cell.accessoryType = UITableViewCellAccessoryCheckmark; 
} else if (![tableView.indexPathsForSelectedRows containsObject:indexPath]) { 
    cell.accessoryType = UITableViewCellAccessoryNone; 
} 

爲我工作

相關問題