【发布时间】:2014-10-01 18:12:03
【问题描述】:
希望各位高手能轻松回答这个问题。
我有一个包含两个子视图的视图:一个 UIImageView 和一个 UILabel。图像视图将保持不变,但标签文本内容会动态变化。我刚刚开始使用自动布局,所以没有太多经验。我希望这两个子视图始终看起来像是分组的,并且无论标签的内容如何,“组”都在其父视图中以 H 和 V 为中心:
+------------------------------------------+
| |
| +-----+ +----------+ |
| | Img | | ShortText| |
| +-----+ +----------+ |
| |
+------------------------------------------+
+------------------------------------------+
| |
| +-----+ +-------------------+ |
| | Img | | LongText | |
| +-----+ +-------------------+ |
| |
+------------------------------------------+
我不确定解决此问题的最佳方法是什么。到目前为止,我将两个子视图添加到一个“占位符”不可见视图(我们称之为 groupView)中,并添加了约束以使其在超级视图中居中。它适用于初始标签文本,但是当文本开始更改时,groupView 原点保持固定并且不会居中。
这是代码:
UIView *containerView = [[UIView alloc] init];
containerView.translatesAutoresizingMaskIntoConstraints = NO;
UIView *groupView = [[UIView alloc] init];
groupView.translatesAutoresizingMaskIntoConstraints = NO;
UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"img"]];
imgView.translatesAutoresizingMaskIntoConstraints = NO;
[groupView addSubview:imgView];
titleLabel = [[UILabel alloc] init];
titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
titleLabel.text = @"Title";
[groupView addSubview:titleLabel];
[containerView addSubview:groupView];
NSDictionary *viewDictionary = NSDictionaryOfVariableBindings(containerView, groupView, imgView, titleLabel);
[groupView addConstraint:[NSLayoutConstraint constraintWithItem:imgView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:groupView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0]];
[groupView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[imgView]-[titleLabel]" options:NSLayoutFormatAlignAllCenterY metrics:nil views:viewDictionary]];
[containerView addConstraint:[NSLayoutConstraint constraintWithItem:groupView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:containerView attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]];
[containerView addConstraint:[NSLayoutConstraint constraintWithItem:groupView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:containerView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0]];
感谢您的帮助。
【问题讨论】:
-
你可以为imageView指定宽高,为contentView和label指定高度,为label指定水平间距。另外增加标签的拥抱优先级。因此,标签宽度会由于其固有尺寸而增加。
标签: ios objective-c autolayout