这只是一个建议,因为总是将其设置为 false 很烦人,只需为 UIView 设置一个包含所有共享设置的函数并每次调用它,
与每次尝试和设置值相比,它节省了时间,而且不那么烦人,
extension UIView {
func notTranslated() {
self.translatesAutoresizingMaskIntoConstraints = false
//Add any additional code.
}
}
//Usage
let view = UIView()
view.notTranslated()
你不能override这个约束属性,因为UIView可能在IB中声明
translatesAutoresizingMaskIntoConstraints 根据apple。
默认情况下,对于您以编程方式创建的任何视图,该属性都设置为 true。如果在 Interface Builder 中添加视图,系统会自动将此属性设置为 false。
想象一下,如果你可以 override 与 extension 发生冲突,如果有其他 UIView 具有相反的值 True || false,那么在我的意见中:强>
Apple 这样做是为了防止与视图约束发生任何冲突,因此如果您不喜欢每次都编写它,只需将其包装在一个函数中即可。
如果有人有其他信息,请不要犹豫,贡献。
更新:我发现this 很酷的答案也可以,请查看下面的代码。
class MyNibless: UIView {
//-----------------------------------------------------------------------------------------------------
//Constructors, Initializers, and UIView lifecycle
//-----------------------------------------------------------------------------------------------------
override init(frame: CGRect) {
super.init(frame: frame)
didLoad()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
didLoad()
}
convenience init() {
self.init(frame: CGRect.zero)
}
func didLoad() {
//Place your initialization code here
//I actually create & place constraints in here, instead of in
//updateConstraints
}
override func layoutSubviews() {
super.layoutSubviews()
//Custom manually positioning layout goes here (auto-layout pass has already run first pass)
}
override func updateConstraints() {
super.updateConstraints()
//Disable this if you are adding constraints manually
//or you're going to have a 'bad time'
//self.translatesAutoresizingMaskIntoConstraints = false
translatesAutoresizingMaskIntoConstraints = false
//Add custom constraint code here
}
}
var nibless: UIView = MyNibless()
//Usage
nibless.updateConstraints()
print(nibless.translatesAutoresizingMaskIntoConstraints) //false
所以只需将MyNibless 实例创建为UIView,这也为自定义打开了大门