2013-09-25 110 views
0
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 

    UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath]; 
    cell.selectionStyle = UITableViewCellSelectionStyleNone; 
    cell.userInteractionEnabled = NO; 
} 

我用上面的代碼在用戶點擊一次後禁用單元格。我遇到的問題是,當一個單元格被添加到表格中時,該新單元格被禁用,並且之前禁用的單元格不再被使用。禁用didSelectRowAtIndexPath中的單元格不起作用?

我該如何解決這個問題?

+1

你爲什麼'cell.userInteractionEnabled = NO;'? – fannheyward

+0

@fannheyward,因爲我不希望該單元格被點擊一次後纔可用。 –

回答

0

當用戶滾動表格時,單元格會重新使用。您需要跟蹤用戶禁用了哪些行,因此在您的cellForRowAtIndexPath中,每次請求時可以爲每個單元設置userInteractionEnabled屬性(根據需要設置爲YES或NO)。

更新 - 更多細節。

您需要跟蹤用戶選擇了哪些索引路徑。添加一個類型爲NSMutableSet的實例變量,並在didSelectRow...方法中爲每個變量添加indexPath

然後在您的cellForRow...方法中,您需要檢查當前的indexPath是否在設置中。根據這個結果,你設置單元格的userInteractionEnabled屬性:

cell.userInteractionEnabled = ![theSelectedPathsSet containsObject:indexPath]; 

其中theSeletedPathsSet是您NSMutableSet實例變量。

該解決方案假定表中的行和部分是固定的。如果用戶可以執行導致行被添加,刪除或移動的事情,那麼您不能簡單地跟蹤索引路徑。您需要使用其他一些密鑰來了解哪些行已被選中。

+0

我不明白:( –

+0

請解釋在哪裏把什麼更好......我真的很困惑,我已經有了一個cellForRowAtIndexPath方法,並且當我在那裏啓用單元格時,那麼禁用代碼不會 –

+0

查看我的更新回答 – rmaddy

0

您在cellForRowAtIndexPath中使用dequeueReusableCellWithIdentifier

你應該有這樣的事情:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
NSString *reuseIdentifier = @"myTableViewCell"; 

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier]; 
if (!cell) { 
     cell = [[ArticleTableViewCell alloc] init]; 
} 
// customise cell here (like cell.title = @"Woopee";) 
if (self.selectedCells containsObject:[NSString stringWithFormat:@"%d", indexPath.row]] { 
    cell.selectionStyle = UITableViewCellSelectionStyleNone; 
    cell.userInteractionEnabled = NO; 
} 
return cell; 
} 

擴大對對方的回答,您可以通過做這樣的事情與跟蹤是否有特定的細胞先前已經選擇(被因此應該被禁用)的以上:

聲明屬性像@property (nonatomic, strong) NSMutableArray *selectedCells;則:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 

    UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath]; 
    [self.selectedCells addObject:[NSString stringWithFormat:@"%d", indexPath.row]]; 
    cell.selectionStyle = UITableViewCellSelectionStyleNone; 
    cell.userInteractionEnabled = NO; 
} 

我的筆記本電腦將死,但如果它墜毀你應該看看初始化單元的代碼(alloc和init),或者保留之前的代碼。

+0

這有助於回答這個問題嗎?基於該行是否被選中來正確設置單元格的「userInteractionEnabled」屬性的代碼在哪裏? – rmaddy

+0

不,我不太確定把這個放在哪裏......我已經有了一個很大的cellforrowatindexpath方法,如果我把它放進去,整個應用程序崩潰。 –

+0

太複雜 –

0

您需要記錄哪些單元格已被禁用。您可以將選定單元格的indexPath存儲在一個數組中,然後使用它來確定哪些單元格應該處於活動狀態並且不在您的單元格中處於活動狀態:forRowAtIndexPath:method。

相關問題