iOS:包含代码和IB的自定义单元格属性不会一起显示

时间:2014-02-17 11:12:41

标签: ios objective-c uitableview storyboard interface-builder

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;
}

上面的代码继续显示labelUsernamecircle。但是,使用IB(labelFirstNamelabelLastName)创建的属性未显示。

所以在viewDidLoad中的tableView.m中,我使用以下代码注册了Nib:

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.tableView registerNib:[UINib nibWithNibName:@"CustomCell"
                                               bundle:[NSBundle mainBundle]]
         forCellReuseIdentifier:@"CustomCell"];
}

现在显示labelFirstNamelabelLastName,但不会显示使用代码(labelUsernamecircle)创建的属性。

如何显示所有4个属性?

2 个答案:

答案 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]];