我想在一个 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/