CustomCell.h
@interface CustomCell : UITableViewCell
//Properties created in Code, not via IB.
@property (nonatomic, strong) UILabel *labelUsername;
@property (nonatomic, strong) UIView *circle;
//Properties Created through IB by control+drag
@property (nonatomic, strong) UILabel *labelFirstName;
@property (nonatomic, strong) UILabel *labelLastName;
@end
CustomCell.m
@implementation CustomCell
-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
//Creating properties in code
self.circle = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 40.0f, 40.0f)];
[self.circle setBackgroundColor:[UIColor brownColor];
self.labelUsername = [[UILabel alloc] initWithFrame:CGRectMake(15, 20, 200.0f, 50.0f)];
self.labelUsername.textColor = [UIColor blackColor];
[self.contentView addSubview:self.labelUsername];
[self.contentView addSubview:self.circle];
}
return self;
}
表视图.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *customCellIdentifier = @"CustomCell";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:customCellIdentifier];
if (cell == nil) {
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:inviteCellIdentifier];
}
cell.labelFirstName.text = @"FirstName";
cell.labelLastName.text = @"LastName";
return cell;
}
上面的代码继续显示labelUsername
和circle
。 但是,使用IB(labelFirstName
和labelLastName
)创建的属性没有出现。
因此,在 viewDidLoad
年的 tableView.m 中,我使用以下代码注册了笔尖:
- (void)viewDidLoad
{
[super viewDidLoad];
[self.tableView registerNib:[UINib nibWithNibName:@"CustomCell"
bundle:[NSBundle mainBundle]]
forCellReuseIdentifier:@"CustomCell"];
}
现在labelFirstName
和labelLastName
出现,但使用代码(labelUsername
和circle
)创建的属性不会出现。
如何显示所有 4 处住宿?
在 CustomCell.m
中试试这个,
- (void)awakeFromNib
{
[super awakeFromNib];
self.circle = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 40.0f, 40.0f)];
[self.circle setBackgroundColor:[UIColor brownColor];
self.labelUsername = [[UILabel alloc] initWithFrame:CGRectMake(15, 20, 200.0f, 50.0f)];
self.labelUsername.textColor = [UIColor blackColor];
[self.contentView addSubview:self.labelUsername];
[self.contentView addSubview:self.circle];
}
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
后试试这个
NSArray *views = [[NSBundle mainBundle]loadNibNamed:@"yourNibName" owner:self options:NULL];
[self addSubview:[views lastObject]];