我在Swift中创建了一个带有相应.xib
文件的自定义UIView子类,但在初始化期间添加自动布局约束时遇到问题。视图本身加载得很好,但添加布局约束似乎对视图的布局没有影响,无论我是否在init
或viewDidMoveToSuperview
或viewDidMoveToWindow
中添加这些约束,即使我之后立即致电setNeedsUpdateConstraints()
/ layoutIfNeeded()
。
我可以在Objective-C中很容易地做到这一点,所以希望这是一个非常简单的修复,但我无法弄清楚我做错了什么。
这是我的代码:
var isLoading = false
class CustomSubview: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private lazy var view: UIView! = { [unowned self] in
let bundle = NSBundle(forClass: self.dynamicType)
let nibName = String(CustomSubview.self)
let nib = UINib(nibName: nibName, bundle: bundle)
return nib.instantiateWithOwner(self, options: nil)[0] as! UIView
}()
private func setup() {
if (isLoading) {
return
}
isLoading = true
// self.view.frame = self.bounds // this works but I want to use Auto Layout
// self.view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight] // this works but I want to use Auto Layout
self.translatesAutoresizingMaskIntoConstraints = false // no effect
addSubview(self.view)
let views = Dictionary(dictionaryLiteral: ("view", self.view))
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[view]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
self.addConstraints(horizontalConstraints)
NSLayoutConstraint.activateConstraints(horizontalConstraints) // this seems to do nothing
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
self.addConstraints(verticalConstraints)
NSLayoutConstraint.activateConstraints(verticalConstraints) // this seems to do nothing
self.setNeedsUpdateConstraints()
self.layoutIfNeeded()
isLoading = false
}
}
答案 0 :(得分:2)
我重新修改了你的课程,使它看起来更清洁。我省略了加载Bool
。此外,我没有从XIB文件创建视图的经验,我几乎没有触及它。
var isLoading = false
class CustomSubview: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private lazy var customView: UIView = {
let bundle = NSBundle(forClass: self.dynamicType)
let nibName = String(CustomSubview.self)
let nib = UINib(nibName: nibName, bundle: bundle)
let customView = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
customView.translatesAutoresizingMaskIntoConstraints = false
return customView
}()
private func setup() {
if (isLoading) {
return
}
isLoading = true
addSubview(self.customView)
let views = ["customView": customView]
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[customView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[customView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
isLoading = false
}
}
对于宽高比约束,您可以为宽高比设置多个约束,并将active
的{{1}}设置为true
/ false
以在它们之间切换。