ios - 以编程方式向 UIView 添加约束

标签 ios swift uiview nslayoutconstraint

我想在一个 View 中添加一个较小的 subview 并为其添加约束。 leading 和 trainling 约束应为 50.0,height 和 botton 应为 80.0。

我以这种方式创建我的 subview

let mySubview = UIView(frame: CGRect(x: 50.0, y: 80.0, width: 540.0, height: 220.0))

然后我尝试使用这段代码将它添加到 View 中

let topConstraint = NSLayoutConstraint(item: mySubview, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: 80.0)
let bottomConstraint = NSLayoutConstraint(item: mySubview, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: 80.0)
let leadingConstraint = NSLayoutConstraint(item: mySubview, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 50.0)
let trailingConstraint = NSLayoutConstraint(item: mySubview, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1, constant: 50.0)

mySubview.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(mySubview)
self.view.addConstraints([topConstraint, bottomConstraint, leadingConstraint, trailingConstraint])
self.view.layoutIfNeeded()

但是约束没有任何作用。 View 在 iPad 上看起来不错,可能是因为第一个 init CGRect(x: 50.0, y: 80.0, width: 540.0, height: 220.0),但在较小的屏幕上它看起来很大。我应该尝试根据屏幕初始化 UIView 还是可以通过添加约束来解决这个问题?

最佳答案

你需要这个:

mySubview.translatesAutoresizingMaskIntoConstraints = false

translatesAutoresizingMaskIntoConstraints is a Boolean value that determines whether the view’s autoresizing mask is translated into Auto Layout constraints.

关于ios - 以编程方式向 UIView 添加约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45811799/

相关文章:

swift - 如何在 Swift 3 中将 NSMutableData 类型的主体添加到请求中?

ios - 如何分离这两个功能?

ios - 为特征改变用户定义的运行时属性

ios - iOS 7 的 UIAlertView/UIAlertController 兼容性

ios - 如何_确切地_将 DTFoundation 集成到另一个 iOS 项目中?

ios - swift Eureka : Can't dynamically hide/show ButtonRow inside cellUpdate

objective-c - 向圆形 View 添加阴影

ios - 在 IOS 中将一个 uiview 的 Action 传递给另一个

ios - 单击 UIAlertController 中的操作时如何更改 UIButton 背景图片?

ios - 检查用户是否安装了 Facebook Messenger iOS 9