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;
}
tableView.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中,我使用以下代码注册了Nib:
- (void)viewDidLoad
{
[super viewDidLoad];
[self.tableView registerNib:[UINib nibWithNibName:@"CustomCell"
bundle:[NSBundle mainBundle]]
forCellReuseIdentifier:@"CustomCell"];
}
现在显示labelFirstName
和labelLastName
,但不会显示使用代码(labelUsername
和circle
)创建的属性。
如何显示所有4个属性?
答案 0 :(得分:0)
在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];
}
答案 1 :(得分:0)
在self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
NSArray *views = [[NSBundle mainBundle]loadNibNamed:@"yourNibName" owner:self options:NULL];
[self addSubview:[views lastObject]];