Fatjon Rrapaj
Fatjon Rrapaj

Reputation: 153

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.

For this, i tried two methods:

1) Subclassing 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:

@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!

Upvotes: 1

Views: 261

Answers (1)

Sulthan
Sulthan

Reputation: 130102

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

Upvotes: 2

Related Questions