2013-06-04 30 views
0

我的書告訴我,我應該使用一個UITableView細胞的複用標識符,像這樣UITableView:如何利用單元重用標識符?

//check for reusable cell of this type 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"]; 

//if there isn't one, create it 
if(!cell){ 
    cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault 
         reuseIdentifier: @"UITableViewCell"]; 
} 

所以從我所看到的,它會檢查,如果我們想要的細胞類型存在,如果是這樣,就會使用它,但如果它沒有,它會創建一個具有所需標識符的。

如果我們有多個單元格樣式(即不同的重用標識符),那麼我們將如何使用它爲我們創建不同的可重用單元格?

+0

然後使用不同的標識符來創建單元格:)'UITableViewCell * cell1 =','UITableViewCell * cell2 ='等 –

回答

3

表視圖管理單元隊列以供每個標識符重用。因此,舉例來說,如果細胞應該有奇數和偶數行(就像一個例子)一個diiferent外觀,你可以做

NSString *cellIdentifier = (indexPath.row % 2 == 0 ? @"EvenCell" : @"OddCell"); 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 
if (cell == nil) { 
    cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault 
         reuseIdentifier:cellIdentifier]; 
    if (indexPath.row % 2 == 0) { 
     // set cell properties for even rows 
    } else { 
     // set cell properties for odd rows 
    } 
} 

使用不同的重用標識符保證從偶數行的單元不重用 作爲奇數行的單元格。

(這個例子只會工作,如果你不插入或刪除單元格。另一個例子是,根據該行的內容不同的細胞。)

0

indexPath,使用它。它包含你的行和部分,所以無論你想要設置什麼屬性,你都可以從行和部分中選擇案例並相應地進行設置。

相關問題