我的 UIView
中有一个 UILabel
对象。我想让这个标签在它的 super View 大小改变时分别移动。这类似于旧的 UIViewAutoresizingFlexibleTopMargin
、UIViewAutoresizingFlexibleRightMargin
、UIViewAutoresizingFlexibleBottomMargin
和 UIViewAutoresizingFlexibleLeftMargin
,因此如果父 View 高度发生变化, label top margin 会分别改变,left margin 也一样。
如何使用 Autolayout
而不是旧的 autoresizingmask
来做到这一点?
最佳答案
您可以使用 NSLayoutConstraint 的 multiplier 属性来实现这一点。您不能将边缘属性与尺寸属性混合使用,但是您可以使用底部和右侧边缘作为尺寸的代理。
UIView * parent = [[UIView alloc] init];
UILabel * label = [[UILabel alloc] init];
[parent addSubview:label];
[label setTranslatesAutoresizingMaskIntoConstraints:NO];
//Label top stays at 20% of the height of the view
NSLayoutConstraint * topMargin = [NSLayoutConstraint constraintWithItem:label
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:parent
attribute:NSLayoutAttributeBottom
multiplier:0.2f
constant:0.0f];
[parent addConstraint:topMargin];
关于iOS:自动布局灵活边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20720576/