简体   繁体   中英

NSLayoutConstraint - dynamic height of a superview

I have three views inside a custom UITableViewCell: self.username, self.postText, self.containerView where self.containerView is the superview for the two others. I want it to be layed out like this:

Contrainer = self.containerView
-----------------------------
|.....5pt-margin............|
| [self.username]           |
| [self.postText]*          |
|.....5pt-margin............|
---------------------------- 
* Posttext can have a dynamic height - and the superview's height should adapt dynamically  based on this height

I've tried the following NSLayoutConstraint in my cell's init method:

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [...]
        NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(self.username,    self.postText, self.containerView);
        [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(5)-[self.username]-[self.postText]-(5)-|" options:0 metrics:nil views:viewsDictionary];
    }
    return self;
}

It currently crashes without any log. How should the correct NSLayoutConstraint look?

When you pass string parameter in constraintsWithVisualFormat: You need to pass ASCII art-like visual format string so In the format @"V:|-(5)-[self.username]-[self.postText]-(5)-|" that you created self.username , self.postText should be of type id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM