[英]Swift cannot set view's height from @IBDesignable class
I am trying to handle view heights for different iPhones (in portrait mode) since XCode considers both iPhone 5 and iPhone XS heights in portrait mode as regular. 由于XCode认为纵向模式下的iPhone 5和iPhone XS高度都是常规的,因此我试图处理不同iPhone(纵向模式)的视图高度。
For this, i tried two methods: 为此,我尝试了两种方法:
1) Subclassing NSLayoutConstraint: 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) Subclassing UIView: 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
}}}
The first one crashes at the setter, the second one has no effects. 第一个在设置器上崩溃,第二个没有影响。 I would appreciate any kind of suggestion. 我将不胜感激任何建议。 Thank you in advance! 先感谢您!
The first one would need the following form: 第一个需要以下格式:
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
}
}
The second one creates a new constraint everytime you call it. 每次调用第二个约束时,都会创建一个新约束。 The constraint is not added to view hierarchy and not activated. 约束不会添加到视图层次结构,也不会激活。 It's released immediately. 立即发布。
It would need the following form: 它将需要以下形式:
// 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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.