How to create an IBInspectable of type enum

前端 未结 6 1436
遇见更好的自我
遇见更好的自我 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:26

    Swift 3

    @IBInspectable var shape:StatusShape = .Rectangle merely creates a blank entry in Interface Builder:

    Use an adapter, which will acts as a bridge between Swift and Interface Builder.
    shapeAdapter is inspectable from IB:

       // IB: use the adapter
       @IBInspectable var shapeAdapter:Int {
            get {
                return self.shape.rawValue
            }
            set( shapeIndex) {
                self.shape = StatusShape(rawValue: shapeIndex) ?? .Rectangle
            }
        }
    

    Unlike the conditional compilation approach (using #if TARGET_INTERFACE_BUILDER), the type of the shape variable does not change with the target, potentially requiring further source code changes to cope with the shape:NSInteger vs. shape:StatusShape variations:

       // Programmatically: use the enum
       var shape:StatusShape = .Rectangle
    

    Complete code

    @IBDesignable
    class ViewController: UIViewController {
    
        enum StatusShape:Int {
            case Rectangle
            case Triangle
            case Circle
        }
    
        // Programmatically: use the enum
        var shape:StatusShape = .Rectangle
    
        // IB: use the adapter
        @IBInspectable var shapeAdapter:Int {
            get {
                return self.shape.rawValue
            }
            set( shapeIndex) {
                self.shape = StatusShape(rawValue: shapeIndex) ?? .Rectangle
            }
        }
    }
    

    ► Find this solution on GitHub.

提交回复
热议问题