How to create an IBInspectable of type enum

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

    For 2020 - @SwiftArchitect answer updated for today:

    Here's a typical full example with all of today's syntax

    import UIKit
    
    @IBDesignable class ClipLabels: UILabel {
        
        enum Side: Int { case left, right }
        
        var side: Side = .left {
            didSet {
                common()
            }
        }
        
        @available(*, unavailable, message: "IB only")
        @IBInspectable var leftRight01: Int {
            get {
                return self.side.rawValue
            }
            set(index) {
                self.side = Side(rawValue: index) ?? .left
            }
        }
        
    

    and just an example of use ...

    switch side {
        case .left:
            textColor = .red
        case .right:
            textColor = .green
        }
    

    For this critical Swift/iOS QA,

    • the very old answer of @SwiftArchitect is perfectly correct but

    • I've just updated it and added the critical "unavailable" thing, which is now possible in Swift.

提交回复
热议问题