When creating new tableView entry the constraints don't work

82 views Asked by At

I have a Master-Detail application that uses CoreData. Everything is hooked up fine and works as expected. There is just one problem with the display when adding a new entry. On the left is the Master's TableView with the entries and on the right is the Detail's View, where the user enters in the new information.

I have a custom UITableViewCell to handle the formatting. The titleLabel of the new entry gets positioned by the constraints correctly. The detailTextLabel however does not seem to care about the constraints and just starts at the top left of the cell (so at the 0,0 position) and thus is on top of the titleLabel.

What am I doing wrong?

Here is the my custom initializer for the custom UITableViewCell:

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {

    self = [super initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier];
    if (self) {

        self.backgroundColor = [UIColor darkGrayColor];
        self.textLabel.font = [Constants mainFontWithSize:16];
        self.detailTextLabel.font = [Constants mainFontWithSize:12];

        // correct default constraints
        self.textLabel.translatesAutoresizingMaskIntoConstraints = NO;
        self.detailTextLabel.translatesAutoresizingMaskIntoConstraints = NO;

        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-15-[textLabel]-35-|" options:0 metrics:nil views:@{ @"textLabel": self.textLabel }]];
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-15-[detailTextLabel]-35-|" options:0 metrics:nil views:@{ @"detailTextLabel": self.detailTextLabel }]];
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-7-[textLabel(19)]-(3)-[detailTextLabel(14)]" options:NSLayoutFormatAlignAllLeft metrics:nil views:@{ @"textLabel": self.textLabel, @"detailTextLabel": self.detailTextLabel }]];


    }
    return self;
}

Thanks

1

There are 1 answers

1
AudioBubble On BEST ANSWER

It looks like you're trying to add constraints to labels for a built-in cell style.

The reason why this doesn't won't work is because they're (public yet) internal labels, and Apple's code is optimized to remove its labels from their contentView when Apple believes the labels won't be needed.

When a label is removed from its superview, constraints are also removed. Later, when Apple adds the label to the superView, the constraints you had added affected the built-in behavior, so its label is now misplaced.

Either let Apple manage and layout its built-in cell styles on its own, or use a custom cell style with your own labels and constraints.