2013-04-02 40 views
5

我有一個UIViewController,在某些時候增長了一個UITableView,當它的時候我只是初始化TableView實例變量並將其添加到視圖中,但我不知道如何處理單元的出隊添加到視圖;我需要一個重用標識符,但我不知道如何設置它。以編程方式添加UITableView - 如何設置單元的重用標識符?

這個方法我該做什麼?

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath]; 

    return cell; 
} 
+0

你在'cellForRowAtIndexPath'的任何實現中都會做同樣的事情。關於您獲得表格視圖的方式沒有任何改變表格視圖的工作方式。你所展示的代碼是一個非常好的開始。你不需要檢查'!cell'就可以從iOS 5上獲得 – matt

回答

7

使用方法initWithStyle:reuseIdentifier

  1. 檢查是否存在cell
  2. 如果沒有,那麼你需要將其初始化。

代碼

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

    if (!cell) 
     cell = [[UITableViewCell alloc] initWithStyle: someStyle reuseIdentifier: cellIdentifier]; 

    return cell; 
} 
+0

。 http://stackoverflow.com/questions/7946840/dequeuereusablecellwithidentifier-behavior-changed-for-prototype-cells –

+0

既然不像IB那樣我可以給所有單元格上的UIViews(UILabel,UIImage等)做一個特定的佈局我必須創建一個UILabel並將其添加到每個單元格的單元格子視圖中? –

+0

您可以創建UITableViewCell的子類並在那裏執行特定的子視圖設置。 – MJN

0

重用標識符不必明確defined.In的cellForRowAtIndexPath方法,你有問題包括定義,是足以與

工作爲Reference

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *MyIdentifier = @"MyReuseIdentifier"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; 
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier]]; 
    } 
    Region *region = [regions objectAtIndex:indexPath.section]; 
    TimeZoneWrapper *timeZoneWrapper = [region.timeZoneWrappers objectAtIndex:indexPath.row]; 
    cell.textLabel.text = timeZoneWrapper.localeName; 
    return cell; 
} 
相關問題