I am trying to create a reusable message UIView
subclass that adjusts its height based on the text inside its UILabel
. This answer says it can't be done. Is that really the case? iOS message cell width/height using auto layout
My issue is that the UILabel's CGFrame
's height is too large. (The UILabel
has a green background color.)
Here's my code (by the way, [autolayoutView]
sets translatesAutoresizingMaskIntoConstraints
to NO
):
SSLStickyView *stickyView = [[SSLStickyView alloc] initWithText:@"Try keeping a steady beat to help me get past the notes! Press the bass drum to jump!"];
SSLStickyView.m
- (instancetype)initWithText:(NSString *)text
{
self = [super initWithFrame:CGRectZero];
if (self)
{
_stickyImageView = [UIImageView autoLayoutView];
_stickyImageView.backgroundColor = [UIColor blueColor];
_stickyImageView.image = [UIImage imageNamed:@"element_sticky"];
[self addSubview:_stickyImageView];
float padding = 5;
NSMutableAttributedString *attributedText =
[[NSMutableAttributedString alloc]
initWithString:text
attributes:@
{
NSFontAttributeName: [UIFont boldSystemFontOfSize:30],
NSForegroundColorAttributeName: [UIColor purpleColor]
}];
UILabel *textLabel = [UILabel autoLayoutView];
textLabel.preferredMaxLayoutWidth = 50;
textLabel.attributedText = attributedText;
textLabel.numberOfLines = 0; // unlimited number of lines
textLabel.lineBreakMode = NSLineBreakByWordWrapping;
textLabel.backgroundColor = [UIColor greenColor];
[_stickyImageView addSubview:textLabel];
NSLayoutConstraint *stickyWidthPin =
[NSLayoutConstraint constraintWithItem:_stickyImageView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:textLabel
attribute:NSLayoutAttributeWidth
multiplier:1
constant:padding * 2];
NSLayoutConstraint *stickyHeightPin =
[NSLayoutConstraint constraintWithItem:_stickyImageView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:textLabel
attribute:NSLayoutAttributeHeight
multiplier:1
constant:0];
NSLayoutConstraint *stickyTextLabelTop =
[NSLayoutConstraint constraintWithItem:_stickyImageView
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:textLabel
attribute:NSLayoutAttributeTop
multiplier:1
constant:0];
NSLayoutConstraint *stickyTextLeftPin = [NSLayoutConstraint constraintWithItem:_stickyImageView
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:textLabel
attribute:NSLayoutAttributeLeft
multiplier:1
constant:-padding * 2];
NSDictionary *views = NSDictionaryOfVariableBindings(_stickyImageView, textLabel);
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[_stickyImageView]" options:0 metrics:nil views:views]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_stickyImageView]" options:0 metrics:nil views:views]];
[self addConstraints:@[stickyWidthPin, stickyHeightPin, stickyTextLeftPin, stickyTextLabelTop]];
self.backgroundColor = [UIColor whiteColor];
}
return self;
}