Xcode 4.2 UITableview自定义单元格

时间:2011-11-28 05:14:30

标签: iphone objective-c uitableview ios5

故事板上的自定义单元格有问题。我需要从名为

的方法访问标签

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

我如何在我的代码中定义它?当我使用IBOutlet然后它可能导致错误。

那么我怎样才能访问像

这样的标签

cell.textlable.text ??

enter image description here

非常感谢。

4 个答案:

答案 0 :(得分:13)

我会继承UITableViewCell。在子类内部创建IBOutlets,然后您可以以常规方式访问它们并在界面构建器中进行设置。只需确保并将原型单元设置为该类。然后出口将出现,你可以用你想要的点语法访问它们。

一个例子是:

@interface CustomCell : UITableViewCell
{
}
@property (nonatomic, retain) IBOutlet UILabel* customLabel;

@end

并且实现同样简单

#import CustomCell.h
@implementation CustomCell

@synthesize customLabel;

@end

就这么简单, 然后在你的方法中你会做这样的事情:

CustonmCell* cell = [tableView dequeueReusableCellWithIdentifier:@"customCell"];
cell.customLabel = //whatever
//or
UILabel* mylabel = cell.customLabel;

您可以根据需要添加任意数量的插座,并以类似的方式访问它们。

答案 1 :(得分:6)

一个常见的解决方案是在故事板中为每个标签添加标签,然后使用viewWithTag:找到标签,在代码中找到它,如下所示:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = blah blah blah ...
    ...
    UILabel *myLabel = [cell viewWithTag:1];
    UILabel *anotherLabel = [cell viewWithTag:2];
    // etc.
}

答案 2 :(得分:1)

对于故事板中的自定义单元格,请使用cellWillDisplay方法而不是cellForRow来访问单元格变量。

步骤1.创建自定义MyTableViewCell:UITableViewCell类。将IBOutlet变量放在此类中。

步骤2.在Xcode IB上,选择单元格,将其类更改为MyTableViewCell。然后链接IBOutlets。

步骤3.在cellWillDisplayAtIndexPath中,照常访问IBOutlet变量cell.myTextLabel。

编辑:更正,如果您使用动态原型,那么cellForRowAtIndexPath将起作用。如果您正在使用静态单元格,请使用cellWillDisplayAtIndexPath。如果您使用静态单元格,则上述步骤不适用,因为您将在UITableView的视图控制器上定义IBOutlets。对不起,感到困惑。

答案 3 :(得分:1)

只是编辑Robs的答案。我花了一段时间,因为它在xcode 4中出现错误。将其更改为:         UILabel * myLabel =(UILabel *)[cell.contentView viewWithTag:1];