【发布时间】:2017-08-22 07:48:01
【问题描述】:
我想在视图中添加一个较小的子视图并向其添加约束。前导和训练约束应为 50.0,高度和底部应为 80.0。
我以这种方式创建我的子视图
let mySubview = UIView(frame: CGRect(x: 50.0, y: 80.0, width: 540.0, height: 220.0))
然后我尝试使用此代码将其添加到视图中
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()
但是这些禁忌没有任何效果。该视图在 iPad 上看起来不错,可能是因为第一个 init CGRect(x: 50.0, y: 80.0, width: 540.0, height: 220.0),但在较小的屏幕上它看起来非常大。我应该尝试根据屏幕初始化 UIView 还是可以通过添加约束来解决这个问题?
【问题讨论】:
标签: ios swift uiview nslayoutconstraint