如何创建的UITableViewCell编程方式使用自动版式自定义 [英] How to create a custom UITableViewCell programmatically using AutoLayout

查看:99
本文介绍了如何创建的UITableViewCell编程方式使用自动版式自定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个UITableView,将类似的行为一个Twitter客户端的时间表。现在,我只是试图获得一个UITableViewCell内的两个标签。所推荐的这个堆栈溢出的答案,我使用的每一个布局不同reuseIdentifier。我的布局很简单,由单标签或两个标签。最后,我会调整UITableViewCells的高度,但首先我需要填充内容的单元格。

我能得到这样的标签显示,如果我设置其帧 initWithFrame:方法,但是约束不是正在实施


  • 问:什么是preventing出现标签和约束?我清楚地失踪在我执行的UITableViewCell的东西,但我不知道它是什么。


  • 次要的问题:我是不是正确的注册UITableViewCell类,在每个reuseIdentifier viewDidLoad中


这可能会遇到方面存在困难,但Interface Builder中混淆了我,我想完成这一切,code。

下面是自定义的code的UITableViewCell命名TVTCell.h:

 静态的NSString * const的kCellIDTitle = @CellWithTitle
静态的NSString * const的kCellIDTitleMain = @CellWithTitleMain@interface TVTCell:的UITableViewCell
{
    * NSString的reuseID;
}@属性(非原子,强)的UILabel * nameLabel;
@属性(非原子,强)的UILabel * mainLabel;@结束

和TVTCell.m:

   - (ID)initWithStyle:(UITableViewCellStyle)风格reuseIdentifier:(* NSString的)reuseIdentifier
{
    自= [超级initWithStyle:风格reuseIdentifier:reuseIdentifier];
    如果(个体经营){
        reuseID = reuseIdentifier;        nameLabel = [[的UILabel的alloc]初始化];
        [nameLabel setTextColor:[的UIColor blackColor]];
        [nameLabel setBackgroundColor:[的UIColor colorWithHue:32饱和度:100亮度:63个字母:1];
        [nameLabel并入setfont:[UIFont fontWithName:@HelveticaNeue尺寸:18.0f]];
        [nameLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
        [self.contentView addSubview:nameLabel];        mainLabel = [[的UILabel的alloc]初始化];
        [mainLabel setTextColor:[的UIColor blackColor]];
        [mainLabel setBackgroundColor:[的UIColor colorWithHue:66饱和度:100亮度:63个字母:1];
        [mainLabel并入setfont:[UIFont fontWithName:@HelveticaNeue尺寸:18.0f]];
        [mainLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
        [self.contentView addSubview:mainLabel];        [self.contentView setTranslatesAutoresizingMaskIntoConstraints:NO];    }
    返回自我;
}
- (无效)updateConstraints
{
    [超级updateConstraints]    *的NSDictionary意见= NSDictionaryOfVariableBindings(nameLabel,mainLabel);
    如果(reuseID == kCellIDTitle){
        NSArray的*约束= [NSLayoutConstraint constraintsWithVisualFormat:@H:| [nameLabel] |
                                                选项​​:NSLayoutFormatAlignAllCenterX
                                                指标:无
                                                  观点:观点];
        [self.contentView addConstraints:约束];
        约束= [NSLayoutConstraint constraintsWithVisualFormat:@V:| [nameLabel] |
                                                              选项​​:NSLayoutFormatAlignAllCenterX
                                                              指标:无
                                                                观点:观点];
        [self.contentView addConstraints:约束];
    }
    如果(reuseID == kCellIDTitleMain){
        NSArray的*约束= [NSLayoutConstraint constraintsWithVisualFormat:@H:| [nameLabel] |
                                                                       选项​​:NSLayoutFormatAlignAllCenterX
                                                                       指标:无
                                                                         观点:观点];
        [self.contentView addConstraints:约束];        约束= [NSLayoutConstraint constraintsWithVisualFormat:@H:| [mainLabel] |
                                                                       选项​​:NSLayoutFormatAlignAllCenterX
                                                                       指标:无
                                                                         观点:观点];
        [self.contentView addConstraints:约束];        约束= [NSLayoutConstraint constraintsWithVisualFormat:@V:| [nameLabel] [mainLabel] |
                                                              选项​​:NSLayoutFormatAlignAllLeft
                                                              指标:无
                                                                观点:观点];
        [self.contentView addConstraints:约束];        [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:nameLabel
                                     属性:NSLayoutAttributeHeight
                                     relatedBy:NSLayoutRelationEqual
                                        toItem:无
                                     属性:NSLayoutAttributeNotAnAttribute
                                    事半功倍:0.0
                                      恒:44.0]];
        [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:nameLabel
                                                                     属性:NSLayoutAttributeWidth
                                                                     relatedBy:NSLayoutRelationEqual
                                                                        toItem:self.contentView
                                                                     属性:NSLayoutAttributeNotAnAttribute
                                                                    事半功倍:0.0
                                                                      常数:1]];
    }
}

对不起,每吨code的。这里是我的UITableView的的tableView:的cellForRowAtIndexPath:

   - (UITableViewCell的*)的tableView:(UITableView的*)的tableView的cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    如果(indexPath.row == 0 || indexPath.row == 2 || indexPath.row == 3){
        TVTCell *电池= [的tableView dequeueReusableCellWithIdentifier:kCellIDTitle forIndexPath:indexPath];        [细胞nameLabel]的setText:[nameArray objectAtIndex:indexPath.row]];        返回细胞;
    }否则如果(indexPath.row == 1 || indexPath.row == 4 || indexPath.row == 5){
        TVTCell *电池= [的tableView dequeueReusableCellWithIdentifier:kCellIDTitleMain forIndexPath:indexPath];        [细胞nameLabel]的setText:[nameArray objectAtIndex:indexPath.row]];
        [细胞mainLabel]的setText:[dataArray中objectAtIndex:indexPath.row]];        返回细胞;
    }其他
    {
        *的UITableViewCell = badCell [UITableViewCell的页头]初始化];
        的NSLog(@警告返回该不应该是这里的小区!);
        badCell.textLabel.text = @警告!
        返回badCell;
    }
}

最后,在UITableView中的viewDidLoad方法:

   - (无效)viewDidLoad中
{
    [超级viewDidLoad中];    [自我的tableView]的registerClass:[TVTCell类] forCellReuseIdentifier:kCellIDTitle];
    [自我的tableView]的registerClass:[TVTCell类] forCellReuseIdentifier:kCellIDTitleMain];
}


解决方案

有几件事情错了你的code。首先,我想你会发现,如果你做一些记录,那updateConstraints不会被调用。我会把所有的code在init方法。此外,有几件事情错在你的约束。是不是需要的地方,你的高度设置为44的约束,因为你已经有了固定的以与电池的底的标签。我不知道你想与最后一个做什么,它看起来像这将使nameLabel 1点宽。此外,你不应该设置translatesAutoresizingMaskIntoConstraints为NO的内容视图,导致怪异的效果。因此,这是code我想你想要的:

   - (ID)initWithStyle:(UITableViewCellStyle)风格reuseIdentifier:(* NSString的)reuseIdentifier {
    自= [超级initWithStyle:风格reuseIdentifier:reuseIdentifier];
    如果(个体经营){
        reuseID = reuseIdentifier;        nameLabel = [[的UILabel的alloc]初始化];
        [nameLabel setTextColor:[的UIColor blackColor]];
        [nameLabel setBackgroundColor:[的UIColor colorWithHue:32饱和度:100亮度:63个字母:1];
        [nameLabel并入setfont:[UIFont fontWithName:@HelveticaNeue尺寸:18.0f]];
        [nameLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
        [self.contentView addSubview:nameLabel];        mainLabel = [[的UILabel的alloc]初始化];
        [mainLabel setTextColor:[的UIColor blackColor]];
        [mainLabel setBackgroundColor:[的UIColor colorWithHue:66饱和度:100亮度:63个字母:1];
        [mainLabel并入setfont:[UIFont fontWithName:@HelveticaNeue尺寸:18.0f]];
        [mainLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
        [self.contentView addSubview:mainLabel];        *的NSDictionary意见= NSDictionaryOfVariableBindings(nameLabel,mainLabel);
        如果(reuseID == kCellIDTitle){
            NSArray的*约束= [NSLayoutConstraint constraintsWithVisualFormat:@H:| [nameLabel] |
                                                                           选项​​:0
                                                                           指标:无
                                                                             观点:观点];
            [self.contentView addConstraints:约束];
            约束= [NSLayoutConstraint constraintsWithVisualFormat:@V:| [nameLabel] |
                                                                  选项​​:0
                                                                  指标:无
                                                                    观点:观点];
            [self.contentView addConstraints:约束];
        }
        如果(reuseID == kCellIDTitleMain){
            NSArray的*约束= [NSLayoutConstraint constraintsWithVisualFormat:@H:| [nameLabel] |
                                                                           选项​​:0
                                                                           指标:无
                                                                             观点:观点];
            [self.contentView addConstraints:约束];            约束= [NSLayoutConstraint constraintsWithVisualFormat:@H:| [mainLabel] |
                                                                  选项​​:0
                                                                  指标:无
                                                                    观点:观点];
            [self.contentView addConstraints:约束];            约束= [NSLayoutConstraint constraintsWithVisualFormat:@V:| [nameLabel] [mainLabel(== nameLabel)|
                                                                  选项​​:0
                                                                  指标:无
                                                                    观点:观点];
            [self.contentView addConstraints:约束];        }
    }
    返回自我;
}

I'm trying to implement a UITableView that will behave similarly to the timeline of a twitter client. Right now I'm simply attempting to get two labels inside a UITableViewCell. As recommended by this Stack Overflow answer, I'm using a different reuseIdentifier for each layouts. My layouts are simple, consisting of either a single label or two labels. Eventually I will be adjusting the height of the UITableViewCells but first I need to get the cells populated with content.

I can get the labels so show up if I set their frame with initWithFrame:, however the constraints aren't being implemented.

  • Question: What is preventing the labels and constraints from appearing? I'm clearly missing something in my implementation of the UITableViewCell but I have no idea what it is.

  • Secondary question: Am I registering the UITableViewCell class correctly for each reuseIdentifier in viewDidLoad?

This might come across as being difficult but Interface Builder confuses me, I would like to accomplish this all in code.

Here is the code for the custom UITableViewCell named TVTCell.h:

static NSString * const kCellIDTitle = @"CellWithTitle";
static NSString * const kCellIDTitleMain = @"CellWithTitleMain";

@interface TVTCell : UITableViewCell
{
    NSString *reuseID;
}

@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *mainLabel;

@end

And TVTCell.m:

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

        nameLabel = [[UILabel alloc] init];
        [nameLabel setTextColor:[UIColor blackColor]];
        [nameLabel setBackgroundColor:[UIColor colorWithHue:32 saturation:100 brightness:63 alpha:1]];
        [nameLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:18.0f]];
        [nameLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
        [self.contentView addSubview:nameLabel];

        mainLabel = [[UILabel alloc] init];
        [mainLabel setTextColor:[UIColor blackColor]];
        [mainLabel setBackgroundColor:[UIColor colorWithHue:66 saturation:100 brightness:63 alpha:1]];
        [mainLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:18.0f]];
        [mainLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
        [self.contentView addSubview:mainLabel];

        [self.contentView setTranslatesAutoresizingMaskIntoConstraints:NO];

    }
    return self;
}


- (void)updateConstraints
{
    [super updateConstraints];

    NSDictionary *views = NSDictionaryOfVariableBindings(nameLabel, mainLabel);
    if (reuseID == kCellIDTitle) {
        NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[nameLabel]|"
                                                options: NSLayoutFormatAlignAllCenterX
                                                metrics:nil
                                                  views:views];
        [self.contentView addConstraints:constraints];
        constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[nameLabel]|"
                                                              options: NSLayoutFormatAlignAllCenterX
                                                              metrics:nil
                                                                views:views];
        [self.contentView addConstraints:constraints];
    }
    if (reuseID == kCellIDTitleMain) {
        NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[nameLabel]|"
                                                                       options: NSLayoutFormatAlignAllCenterX
                                                                       metrics:nil
                                                                         views:views];
        [self.contentView addConstraints:constraints];

        constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[mainLabel]|"
                                                                       options: NSLayoutFormatAlignAllCenterX
                                                                       metrics:nil
                                                                         views:views];
        [self.contentView addConstraints:constraints];

        constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[nameLabel][mainLabel]|"
                                                              options: NSLayoutFormatAlignAllLeft
                                                              metrics:nil
                                                                views:views];
        [self.contentView addConstraints:constraints];

        [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:nameLabel
                                     attribute:NSLayoutAttributeHeight
                                     relatedBy:NSLayoutRelationEqual
                                        toItem:nil
                                     attribute:NSLayoutAttributeNotAnAttribute
                                    multiplier:0.0
                                      constant:44.0]];
        [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:nameLabel
                                                                     attribute:NSLayoutAttributeWidth
                                                                     relatedBy:NSLayoutRelationEqual
                                                                        toItem:self.contentView
                                                                     attribute:NSLayoutAttributeNotAnAttribute
                                                                    multiplier:0.0
                                                                      constant:1]];
    }
}

Sorry, ton of code. Here's my UITableView's tableView:cellForRowAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0 || indexPath.row == 2 || indexPath.row == 3) {
        TVTCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIDTitle forIndexPath:indexPath];

        [[cell nameLabel] setText:[nameArray objectAtIndex:indexPath.row]];

        return cell;
    } else if (indexPath.row == 1 || indexPath.row == 4 || indexPath.row == 5) {
        TVTCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIDTitleMain forIndexPath:indexPath];

        [[cell nameLabel] setText:[nameArray objectAtIndex:indexPath.row]];
        [[cell mainLabel] setText:[dataArray objectAtIndex:indexPath.row]];

        return cell;
    } else
    {
        UITableViewCell *badCell = [[UITableViewCell alloc] init];
        NSLog(@"Warning! returning a cell that shouldnt be here");
        badCell.textLabel.text = @"Warning!";
        return badCell;
    }
}

And lastly, the UITableView's viewDidLoad method:

- (void)viewDidLoad
{
    [super viewDidLoad];

    [[self tableView] registerClass:[TVTCell class] forCellReuseIdentifier:kCellIDTitle];
    [[self tableView] registerClass:[TVTCell class] forCellReuseIdentifier:kCellIDTitleMain];
}

解决方案

There are several things wrong with your code. First, I think you'll find, if you do some logging, that updateConstraints is never called. I would put all the code in the init method. Also, there are several things wrong in your constraints. The constraint where you set the height to 44 is not needed since you already have the labels pinned to the to and bottom of the cell. I don't know what you're trying to do with that last one, it looks like that would make the nameLabel 1 point wide. Also, you shouldn't set the translatesAutoresizingMaskIntoConstraints to NO for the content view, that causes weird effects. So this is the code I think you want:

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

        nameLabel = [[UILabel alloc] init];
        [nameLabel setTextColor:[UIColor blackColor]];
        [nameLabel setBackgroundColor:[UIColor colorWithHue:32 saturation:100 brightness:63 alpha:1]];
        [nameLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:18.0f]];
        [nameLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
        [self.contentView addSubview:nameLabel];

        mainLabel = [[UILabel alloc] init];
        [mainLabel setTextColor:[UIColor blackColor]];
        [mainLabel setBackgroundColor:[UIColor colorWithHue:66 saturation:100 brightness:63 alpha:1]];
        [mainLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:18.0f]];
        [mainLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
        [self.contentView addSubview:mainLabel];

        NSDictionary *views = NSDictionaryOfVariableBindings(nameLabel, mainLabel);
        if (reuseID == kCellIDTitle) {
            NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[nameLabel]|"
                                                                           options: 0
                                                                           metrics:nil
                                                                             views:views];
            [self.contentView addConstraints:constraints];
            constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[nameLabel]|"
                                                                  options: 0
                                                                  metrics:nil
                                                                    views:views];
            [self.contentView addConstraints:constraints];
        }
        if (reuseID == kCellIDTitleMain) {
            NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[nameLabel]|"
                                                                           options:0
                                                                           metrics:nil
                                                                             views:views];
            [self.contentView addConstraints:constraints];

            constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[mainLabel]|"
                                                                  options: 0
                                                                  metrics:nil
                                                                    views:views];
            [self.contentView addConstraints:constraints];

            constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[nameLabel][mainLabel(==nameLabel)]|"
                                                                  options: 0
                                                                  metrics:nil
                                                                    views:views];
            [self.contentView addConstraints:constraints];

        }
    }
    return self;
}

这篇关于如何创建的UITableViewCell编程方式使用自动版式自定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆