2011-02-18 93 views
0

好吧,爲UITableViewController的標準模板代碼,我一直在使用cellForRowAtIndexPath:設置我的UITableViewCells基於數據源。cellForRowAtIndexPath和單元格配置

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
//cell setup 
cell.textLabel.text = @"Initial Data!"; 
return cell; 
} 

但是,這突然讓我覺得這是一個有問題的做法。舉例來說,可以說,我想這樣做

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    //some processing or data update is done here 
    //now I want to update the cell 
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 
    cell.textLabel.text = @"New Data"; 
} 

看起來這是浪費的代碼,因爲檢索的細胞更新,導致它被更新在的cellForRowAtIndexPath代碼中的第二次。

所以我應該把配置小區別的地方,把它一些其他的方式,或者我應該以更聰明的方式寫在cellForRowAtIndexPath配置,以便給它一個簡單的通話將更新UI withou

+0

我認爲你的問題被切斷了。 – jakev 2011-02-18 21:44:44

回答

1

也許改變數據是一個更好的主意。

我假設你會從數組中獲取數據?然後更改didSelectRowAtIndexPath方法中的數據並重新加載所選單元格。

1

通常我會保留一個自我陣列以將必要的數據應用於單元格。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    //cell setup 
    MyObject *obj = ...; ///< retrieve obj from somewhere 
    cell.textLabel.text = obj.text; 
    return cell; 
} 

然後,選擇時,我將修改我的數據源。

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

    NSString *newData = @"New Data"; ///< 

    // Update data source 
    MyObject *obj = ...; 
    obj.text = newData; 

    // Update UI 
    .... 
} 

我寧願讓MyObject來處理事情有關數據處理,例如,可獲得小區的縮略圖中的一個線索,或計算複雜性的結果。控制器將結合數據和UI。

相關問題