我有一堆UILabel,我想添加到我的自定义UITableViewCell类中。我知道如何使用IBOutlets做到这一点,但我只是想知道为什么以这种方式通过编程方式这样做对我不起作用。这是我的自定义UITableViewCell类的代码。
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
_nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 45)];
[_nameLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:23.0]];
[_nameLabel setTextColor:[UIColor blackColor]];
[self addSubview:_nameLabel];
_artistLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 50, 91, 21)];
[_artistLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:15.0]];
[_artistLabel setTextColor:[UIColor blackColor]];
_artistLabel.textAlignment = NSTextAlignmentCenter;
[self addSubview:_artistLabel]; }
return self;
}
另外,我还将附加使用该单元格的UITableView子类的代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
SKItemCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
SKItemDoc *item = [self.items objectAtIndex:indexPath.row];
cell.nameLabel.text = item.data.title;
cell.artistLabel.text = item.data.artist;
return cell;
}
在自定义单元格初始化方法中。您需要为添加标签self.contentView
。改成
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
_nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 45)];
[_nameLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:23.0]];
[_nameLabel setTextColor:[UIColor blackColor]];
[self.contentView addSubview:_nameLabel];
_artistLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 50, 91, 21)];
[_artistLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:15.0]];
[_artistLabel setTextColor:[UIColor blackColor]];
_artistLabel.textAlignment = NSTextAlignmentCenter;
[self.contentView addSubview:_artistLabel]; }
return self;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句