How to create an IBInspectable of type enum

前端 未结 6 1440
遇见更好的自我
遇见更好的自我 2020-12-04 11:56

enum is not an Interface Builder defined runtime attribute. The following does not show in Interface Builder\'s Attributes Inspector:



        
6条回答
  •  春和景丽
    2020-12-04 12:24

    This is an old thread but useful. I have adapted my answer to swift 4.0 and Xcode 9.0 - Swift 4 has its own little issues with this problem. I am having an @IBInspectable variable with enum type and Xcode 9.0 is not happy, showing me this "Property cannot be marked @IBInspectable because its type cannot be representing in Objective-c"

    @Eporediese answers this problem (for swift3) in part; using a property for the storyboard but a straight enum for the rest of the code. Below is a more complete code set that gives you a property to work with in both cases.

    enum StatusShape: Int {
      case Rectangle = 0
      case Triangle = 1
      case Circle = 2
    }
    var _shape:StatusShape = .Rectangle  // this is the backing variable
    
    #if TARGET_INTERFACE_BUILDER
      @IBInspectable var shape: Int {    // using backing variable as a raw int
    
        get { return _shape.rawValue }
        set {
          if _shape.rawValue != newValue {
            _shape.rawValue = newValue
          }
        }
    }
    #else
    var shape: StatusShape {  // using backing variable as a typed enum
      get { return _shape }
      set {
        if _shape != newValue {
          _shape = newValue
        }
      }
    }
    #endif
    

提交回复
热议问题