Swift 无法从 @IBDesignable 设置视图的高度 class

Swift cannot set view's height from @IBDesignable class

我正在尝试处理不同 iPhone 的视图高度(在纵向模式下),因为 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
   }
}

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

需要以下表格:

// 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
    }
 }