【发布时间】:2014-08-02 22:30:01
【问题描述】:
我正在尝试创建一个可重用的消息UIView 子类,该子类根据其UILabel 中的文本调整其高度。这个答案说它不能完成。真的是这样吗? iOS message cell width/height using auto layout
我的问题是 UILabel 的 CGFrame 的高度太大。 (UILabel 的背景颜色为绿色。)
这是我的代码(顺便说一下,[autolayoutView] 将 translatesAutoresizingMaskIntoConstraints 设置为 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;
}
【问题讨论】:
标签: ios objective-c uilabel autolayout nslayoutconstraint