iOS:自动布局灵活边距

标签 ios autolayout

我的 UIView 中有一个 UILabel 对象。我想让这个标签在它的 super View 大小改变时分别移动。这类似于旧的 UIViewAutoresizingFlexibleTopMarginUIViewAutoresizingFlexibleRightMarginUIViewAutoresizingFlexibleBottomMarginUIViewAutoresizingFlexibleLeftMargin,因此如果父 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/

相关文章:

objective-c - 如何在直线的路径中找到一个点

ios - 在 View 期间更改后重新排列 autoLayout

ios - 如何使用 AutoLayout 使我的 UIImage 的高度与我的 UILabel 的固有高度相同?

ios - 以编程方式从 super View 中删除 View 后更新约束/框架(自动布局)

ios - Telegram新源代码APP ID问题(CONNECTION_API_ID_INVALID)

ios - 如何将 Storyboard 中的 socket 连接到 UITableViewCell 类 Xcode 11

ios - 无法在 iPhone 上滚动 heroku 维护页面

ios - 使用 "width"时忽略 UIImageView 的 "Aspect Fill"约束(Xcode,自动布局)

ios - 以编程方式一个接一个地添加 View

ios - ARC环境下类型转换导致编译错误