iOS:带有代码和 IB 的自定义单元格属性不会同时显示



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

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

因此,在 viewDidLoad 年的 tableView.m 中,我使用以下代码注册了笔尖:

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

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

如何显示所有 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]];

最新更新