Swift无法通过@IBDesignable类设置视图的高度

时间:2018-11-17 09:16:02

标签: ios iphone swift nslayoutconstraint

由于XCode认为纵向模式下的iPhone 5和iPhone XS高度都是常规的,因此我试图处理不同iPhone(纵向模式)的视图高度。

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

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

    }}}

第一个在设置器上崩溃,第二个没有影响。 我将不胜感激任何建议。 预先谢谢你!

1 个答案:

答案 0 :(得分:2)

第一个需要以下格式:

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