gpt4 book ai didi

swift - 有什么办法可以永久退出自动调整大小?

转载 作者:搜寻专家 更新时间:2023-10-31 22:53:15 26 4
gpt4 key购买 nike

我正在编写无 nib View ,其中我对所有布局逻辑使用自动布局。我发现自己必须关闭每个实例化 View 的自动调整大小。我的代码中有很多这样的东西:

view.translatesAutoresizingMaskIntoConstraints

理想情况下我只想

extension UIView/NSView {
override var translatesAutoresizingMaskIntoConstraints: Bool = false
}

并一劳永逸地解决它,但扩展不能覆盖存储的属性。

是否有其他一些简单的方法可以永久关闭自动调整大小?

最佳答案

这只是一个建议,因为总是将其设置为 false 很烦人,只需为 UIView 设置一个具有所有共享设置的函数并每次调用它,与每次都尝试和设置值相比,它节省了时间,也没有那么烦人,

extension UIView {
func notTranslated() {
self.translatesAutoresizingMaskIntoConstraints = false
//Add any additional code.
}
}
//Usage
let view = UIView()
view.notTranslated()

您不能覆盖此约束属性,因为UIView 可能在IB

中声明

translatesAutoresizingMaskIntoConstraints 根据 apple .

By default, the property is set to true for any view you programmatically create. If you add views in Interface Builder, the system automatically sets this property to false.

想象一下,如果您可以从 extensionoverride ,如果有其他 UIView 具有相反的功能,这将导致一些冲突值(value)真|| false,所以在我的意见中:

Apple did this to prevent any conflicts with the views constrains, therefore if you don't like to write it every time just wrap it up in a function.

如果有人有更多信息,请不要犹豫,提供帮助。

更新:我找到了 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,这也为自定义打开了大门

关于swift - 有什么办法可以永久退出自动调整大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55213273/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com