[英]Updating Frame/Constraints for programmatically added UIView on orientation change
我有一个UIView,我正在viewDidLoad中使用以下代码以编程方式添加
dropMenuView = YNDropDownMenu(frame: CGRect(x: 0.0, y: 0, width: UIScreen.main.bounds.width, height: 40.0), dropDownViews: [typeView, brandView, priceView], dropDownViewTitles:["Type", "Brand", "Price"])
self.view.addSubview(dropMenuView)
上面的代码创建了一个具有当前方向正确宽度的视图,但是如果用户更改其设备方向,则视图的宽度不会更新。 我尝试在viewWillTransitionTo中添加新的约束:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
let widthConstraint = NSLayoutConstraint(item: dropMenuView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100)
dropMenuView.addConstraints([widthConstraint])
dropMenuView.layoutIfNeeded()
}
我在上面的代码中尝试了多种变体,以使其正常工作。 通常我得到的错误是:'NSLayoutConstraint>:未知的布局属性'
我忍不住以为我正在以错误的方式来解决这个问题。 在方向上增加新的限制会改变前进的方向吗? 在添加子视图之后,我尝试仅添加等宽约束,但是出现相同的错误。 我以前从未真正以编程方式添加约束,所以这些对我来说是未知的。 最好的方法是什么?
在方向更改期间添加约束不是一个好主意。 如果要这样做,则需要删除以前添加的约束,以避免过度约束视图。
您尝试创建的约束不正确。 仅当将nil
作为第二个视图传递时,才使用.notAnAttrubute
。
我建议您改用布局锚。 它们更容易读写:
dropMenuView = YNDropDownMenu(frame: CGRect.zero, dropDownViews: [typeView, brandView, priceView], dropDownViewTitles:["Type", "Brand", "Price"])
self.view.addSubview(dropMenuView)
// you need to set this if you are adding your own constraints and once
// yet set it, the frame is ignored (which is why we just passed CGRect.zero
// when creating the view)
dropMenuView.translatesAutoresizingMaskIntoConstraints = false
// Create the constraints and activate them. This will set `isActive = true`
// for all of the constraints. iOS knows which views to add them to, so
// you don't have to worry about that detail
NSLayoutConstraint.activate([
dropMenuView.topAnchor.constraint(equalTo: view.topAnchor),
dropMenuView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
dropMenuView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
dropMenuView.heightAnchor.constraint(equalToConstant: 40)
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.