以编程方式自定义表视图单元格



我有不使用故事板或xib的源代码。它包含一个UITableView,单元格使用标准的cell.textlabel。

我想要的是使用自定义的 TableViewCell,通常我会创建一个 UITableViewCell 类并在故事板中连接它们,但我不能在这里连接它们,因为它不使用故事板或 xib。

我有以下 UITableViewClass

@interface chatCell : UITableViewCell
@property(nonatomic, weak) IBOutlet UIImageView *homeTeamImage;
@property(nonatomic, weak) IBOutlet UILabel *homeTeamLabel;
@property(nonatomic, weak) IBOutlet UIImageView *awayTeamImage;
@property(nonatomic, weak) IBOutlet UILabel *awayTeamLabel;
@end

如何将它们放置在 TableViewCell 中并将它们连接到属性?

所以我可以开始使用

cell.homeTeamImage
cell.homeTeamLabel
cell.awayTeamImage
cell.awayTeamLabel

您不需要使用 IBOutlet,因为您不想使用 IB 中的属性

@interface chatCell : UITableViewCell
{
    UIImageView *homeTeamImage;
    UILabel *homeTeamLabel;
    UIImageView *awayTeamImage;
    UILabel *awayTeamLabel;
}
@property(nonatomic, weak) UIImageView *homeTeamImage;
@property(nonatomic, weak) UILabel *homeTeamLabel;
@property(nonatomic, weak) UIImageView *awayTeamImage;
@property(nonatomic, weak) UILabel *awayTeamLabel;
@end

不要忘记

@synthesize homeTeamImage, ...; 

在实现文件中。

您可以覆盖 - (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath.无需返回标准的UITableViewCell,您可以返回您的

- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    chatCell c = [[chatCell alloc] init];
    return c;
}

您不需要 IBOutlet 关键字:它不是一种类型,仅在使用情节提要时由 xcode 使用。我认为如果没有故事板,您应该将属性更改为强指针,因为没有其他人强烈指向它们,因此它们将被删除。

如果您使用 xcode 5,则@synthesize不是强制性的。仅当您同时覆盖属性的二传手和获取者时,才需要它。

请参阅《

适用于 iOS 的表视图编程指南》中的以编程方式将子视图添加到单元格的内容视图。在此示例中,单元格是用tableView:cellForRowAtIndexPath:创建的,但您可以在 UITableViewCell 子类中使用相同的方法(在单元格的内容视图上添加视图)。

@interface chatCell : UITableViewCell
{
    UIImageView *homeTeamImage;
    UILabel *homeTeamLabel;
    UIImageView *awayTeamImage;
    UILabel *awayTeamLabel;
}
@property(nonatomic, weak) UIImageView *homeTeamImage;
@property(nonatomic, weak) UILabel *homeTeamLabel;
@property(nonatomic, weak) UIImageView *awayTeamImage;
@property(nonatomic, weak) UILabel *awayTeamLabel;
@end

and don't forget to
    enter code here
@synthesize "All properties"