gpt4 book ai didi

ios - Swift 无法从@IBDesignable 类设置 View 的高度

转载 作者:搜寻专家 更新时间:2023-11-01 06:55:57 24 4
gpt4 key购买 nike

我正在尝试处理不同 iPhone(纵向模式下)的 View 高度,因为 XCode 将纵向模式下的 iPhone 5 和 iPhone XS 高度视为常规。

为此,我尝试了两种方法:

1) 子类化 NSLayoutConstraint:

    @IBDesignable class AdaptiveConstraint: NSLayoutConstraint { 

@IBInspelctable override var constant: CGFloat {
get { return self.constant }
set { self.constant = newValue + A_VARIABLE_I_USE_BASED_ON_IPHONE_TYPE }}}

2) 子类化 UIView:

@IBDesignable class AttributedView: UIView {

@IBInspectable var height: CGFloat {
get {
return self.heightAnchor.constraint(equalToConstant: self.bounds.height).constant
}
set {
self.heightAnchor.constraint(equalToConstant: self.bounds.height).constant = newValue + A_VARIABLE_I_USE_BASED_ON_IPHONE_TYPE

}}}

第一个在 setter 处崩溃,第二个没有效果。我将不胜感激任何建议。提前致谢!

最佳答案

第一个需要以下表格:

override var constant: CGFloat {
get {
// note we are calling `super.`, added subtract for consistency
return super.constant - A_VARIABLE_I_USE_BASED_ON_IPHONE_TYPE
}
set {
// note we are calling `super.`
super.constant = newValue + A_VARIABLE_I_USE_BASED_ON_IPHONE_TYPE
}
}

第二个在您每次调用时都会创建一个新约束。约束未添加到 View 层次结构且未激活。立即发布。

它需要以下形式:

// it would be better to create and add it in viewDidLoad though
lazy var heightConstraint: NSLayoutConstraint = {
let constraint = self.heightAnchor.constraint(equalToConstant: self.bounds.height)
constraint.isActive = true
return constraint
}()

@IBInspectable var height: CGFloat {
get {
return self.heightConstraint.constant - A_VARIABLE_I_USE_BASED_ON_IPHONE_TYPE
}
set {
self.heightConstraint.constant = newValue + A_VARIABLE_I_USE_BASED_ON_IPHONE_TYPE
}
}

关于ios - Swift 无法从@IBDesignable 类设置 View 的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53349817/

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