2013-04-02 39 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; 
} 
相关问题