[英]Xcode 4.2 UITableview Custom cell
故事板上的自定义单元格有问题。 我需要从被调用的方法访问标签
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
我如何在我的代码中定义它? 当我使用IBOutlet然后它可能导致错误。
那我该如何访问标签呢
cell.textlable.text ??
非常感谢。
我会继承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;
您可以根据需要添加任意数量的插座,并以类似的方式访问它们。
一个常见的解决方案是在storyboard中为每个标签viewWithTag:
一个标签,然后使用viewWithTag:
找到标签viewWithTag:
在你的代码中找到它,如下所示:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = blah blah blah ...
...
UILabel *myLabel = [cell viewWithTag:1];
UILabel *anotherLabel = [cell viewWithTag:2];
// etc.
}
对于故事板中的自定义单元格,请使用cellWillDisplay方法而不是cellForRow来访问单元格变量。
步骤1.创建自定义MyTableViewCell:UITableViewCell类。 将IBOutlet变量放在此类中。
步骤2.在Xcode IB上,选择单元格,将其类更改为MyTableViewCell。 然后链接IBOutlets。
步骤3.在cellWillDisplayAtIndexPath中,像往常一样访问IBOutlet变量cell.myTextLabel。
编辑:更正,如果你使用动态原型,那么cellForRowAtIndexPath将工作。 如果您正在使用静态单元格,请使用cellWillDisplayAtIndexPath。 如果您使用静态单元格,则上述步骤不适用,因为您将在UITableView的视图控制器上定义IBOutlets。 对困惑感到抱歉。
只是编辑Robs的答案。 我花了一段时间,因为它在xcode 4中出现错误。将其更改为:UILabel * myLabel =(UILabel *)[cell.contentView viewWithTag:1];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.