我正在尝试构建一个可重用的 UIView
,其宽度应等于 Swift 中的 super View 。
由于其 super View 的大小不同,我想我必须使用自动布局为其设置约束。
但我不知道如何在 Swift 中以编程方式完成它。
这是可重用 subview 的代码:
import UIKit
class bottomMenu: UIView {
@IBOutlet var bottomMenu: UIView!
required init(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
NSBundle.mainBundle().loadNibNamed("bottomMenu", owner: self, options: nil)
bottomMenu.backgroundColor = UIColor.redColor()
//How to make the width of the bottom Menu equal to its superview?
self.addSubview(self.bottomMenu)
}
}
谁能教我怎么做吗?
谢谢
最佳答案
您可以重写 UIView 子类中的 didMoveToSuperview()
方法并在其中添加约束:
override func didMoveToSuperview() {
super.didMoveToSuperview()
backgroundColor = UIColor.redColor()
let views = ["view" : self];
self.setTranslatesAutoresizingMaskIntoConstraints(false)
self.superview?.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[view]|", options: NSLayoutFormatOptions(0), metrics: nil, views: views))
self.superview?.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options: NSLayoutFormatOptions(0), metrics: nil, views: views))
}
关于ios - 如何在 Swift 中使用自动布局设置可重用 UIView 的约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30706405/