IOS - 使用Interface Builder设计UITableView Cell的最佳方式

时间:2013-08-15 20:32:47

标签: ios uitableview interface-builder

嘿,我已经阅读了一些关于样式细胞的教程和文章。由于界面构建器的样式功能有限,我被迫研究其他方法,并且在尝试找到以编程方式设置在界面构建器中创建的UITableViewCell的正确方式时,会留下相互矛盾的感觉。一些来源直接在cellForRowAtIndexPath其他人的样式中设置样式,建议在.m中为UITableViewCell类进行。在cellForRowAtIndexPath中设置样式时遇到了一些性能问题,所以现在我在类.m文件中设置样式。以下是样式的代码:

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];

    if (self)
    {
        NSLog(@"test!");

        _nameLabel.font = [UIFont fontWithName:@"Gotham Light" size:16];
        _locationLabel.font = [UIFont fontWithName:@"Gotham Light" size:14];
        _titleLabel.font = [UIFont fontWithName:@"Gotham Light" size:12];

        [_thumbnailUserImage.layer setCornerRadius:24];
        [_thumbnailUserImage.layer setBorderWidth:2];
        [_thumbnailUserImage.layer setBorderColor:[[UIColor whiteColor] CGColor]];
        [_thumbnailUserImage.layer setMasksToBounds:YES];
        self.contentView.backgroundColor = [UIColor colorWithRed:(247/255.0) green:(245/255.0) blue:(242/255.0) alpha:1];
    }

    return self;
}

这是我创建每个cellForRowAtIndexPath的地方:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    User *user;
    ContactsCell *cell = [[ContactsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    cell = (ContactsCell *)[tableView dequeueReusableCellWithIdentifier:@"ContactsCell"];
    user = [users objectAtIndex:indexPath.row];

    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ContactsCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }

    cell.nameLabel.text = [NSString stringWithFormat: @"%@ %@", user.firstName, user.lastName];
    cell.titleLabel.text = [NSString stringWithFormat:@"%@", user.position];
    cell.locationLabel.text = [NSString stringWithFormat:@"%@", user.location];

    [cell.thumbnailImageView setImageWithURL:[NSURL URLWithString: user.profileUrl] placeholderImage:[UIImage imageNamed:@"stockProfilePhoto.png"]];

    return cell;
}

由于某种原因,上面的代码实际上并不起作用,我只是成功地直接在cellForRowAtIndexPath委托方法中设置了单元格样式。所以在我尝试解决这个问题之前我想知道,我应该在哪里放置使用<QuartzCore/QuartzCore.h>的单元格样式以及其他无法通过界面构建​​器编辑的库?如果正确的答案是我正在进行的那个,那么样式怎么没有出现? “测试!”出现在每个创建的单元格中,因此我知道initWithStyle方法已被覆盖并正在执行。

1 个答案:

答案 0 :(得分:6)

如果您在界面构建器中执行任何操作,则无法使用initWithStyle。请改用awakeFromNib。

override for custom UITableViewCell