92

I'd like to create @IBInspectable element as you see at the picture below :

enter image description here

my idea is to use something like enum as type for @IBInspectable, but it looks like it's not the case, any ideas how to implement element like this ?

EDIT:

It looks like @IBInspectable supports only these types :

  • Int
  • CGFloat
  • Double
  • String
  • Bool
  • CGPoint
  • CGSize
  • CGRect
  • UIColor
  • UIImage

bummer

5
  • A workaround, of sorts, is to put an inspectable computed property in front of the value you want to set. Of course, it still won't magically appear as a pop-up menu of enumerated values in Interface Builder; but at least you can define an inspectable value and use it to set an enum.
    – matt
    Feb 26, 2015 at 18:16
  • 9
    At WWDC this year, I asked an Apple engineer in the Developer Tools lab about this. He said that he agreed it would be a great feature, but it is not currently possible. He suggested I file a radar at bugreport.apple.com which I did. It was closed as a duplicate of issue 15505220 but I would highly recommend people putting in similar issues. These things often get addressed if enough people complain. Nov 10, 2016 at 21:56
  • 1
    how is this question different from stackoverflow.com/questions/27432736/… Jan 5, 2017 at 15:57
  • Possible duplicate of How to create an IBInspectable of type enum Feb 4, 2017 at 21:19
  • And with SwiftUI and the new Canvas in Xcode 11, it seems this will never be on Apple's roadmap
    – Ky -
    Sep 18, 2019 at 15:54

7 Answers 7

27

That's not possible (for now). You can only use those types that you see in User Defined Runtime Attributes section.

From Apple's doc:

You can attach the IBInspectable attribute to any property in a class declaration, class extension, or category for any type that’s supported by the Interface Builder defined runtime attributes: boolean, integer or floating point number, string, localized string, rectangle, point, size, color, range, and nil.

2
  • 2
    When I want to use an enum, I give the enum values explicit assignments ( = 1, = 2, etc.). And in the handler, I add an assertion if the value from IB is not one of the values from the enum. Annoying that enums aren't supported, but this trick makes them more usable, at least. Feb 26, 2015 at 18:17
  • An enum is an integer. Feb 26, 2015 at 20:00
24

Another work-around for this is to alter how an enumeration property appears to interface builder. For example:

#if TARGET_INTERFACE_BUILDER
@property (nonatomic, assign) IBInspectable NSInteger fontWeight;
#else
@property (nonatomic, assign) FontWeight fontWeight;
#endif

This assumes an enum called FontWeight. It relies on the fact that enums and their raw integer values can be used somewhat interchangeably in Objective-C. After doing this you are able to specify an integer in Interface builder for the property which is not ideal, but works, and retains a small amount of type safety when using the same property programatically.

This is a better alternative than declaring a separate integer property because you don't need to write extra logic to handle a second integer property which could also be used to accomplish the same thing.

However, this does not work with Swift because we're not able to implicitly cast from an integer to an enum. Any thoughts on solving that would be appreciated.

1
  • 4
    I really thought this did work in Swift, but in further testing... no Nov 1, 2015 at 0:53
7

I do this using a Inspectable NSInteger value and override the setter to allow it to set the enum. This has the limitation of not using a popup list and if you change your enum values, then the interface options will not update to match.

Example.

In Header File:

typedef NS_ENUM(NSInteger, LabelStyle)
{
    LabelStyleContent = 0, //Default to content label
    LabelStyleHeader,
};

...

@property LabelStyle labelStyle;
@property (nonatomic, setter=setLabelAsInt:) IBInspectable NSInteger labelStyleLink;

In the implementation file:

- (void)setLabelAsInt:(NSInteger)value
{
    self.labelStyle = (LabelStyle)value;
}

You could optionally add some logic in there to ensure that it is being set to a valid value

2
  • Not sure why this was down voted. Seems like a good way to get around the problem.
    – Fogmeister
    Oct 15, 2015 at 10:58
  • Thank you @Fogmeister - I am actually using this implementation inside an app at the moment :) Dec 3, 2015 at 16:53
4

Sikhapol is correct, enums are not yet supported also not in xCode 9. I believe the safest approach is to use enums as strings and implement a "shadow" (private) IBInspectable var. Here is an example of a BarBtnPaintCode item which represents a barbutton item that can be styled with a custom icon (that is done using PaintCode) right inside Interface Builder (swift 4).

In interface build you just enter the string (identical to the enum value), which keeps it clear (if you are entering numbers nobody knows what they mean)

class BarBtnPaintCode: BarBtnPaintCodeBase {

    enum TypeOfButton: String {
        case cancel
        case ok
        case done
        case edit
        case scanQr
        //values used for tracking if wrong input is used
        case uninitializedLoadedFromStoryboard
        case unknown
    }

    var typeOfButton = TypeOfButton.uninitializedLoadedFromStoryboard

    @IBInspectable private var type : String {
        set {
            typeOfButton = TypeOfButton(rawValue: newValue) ?? .unknown
            setup()
        }
        get {
            return typeOfButton.rawValue
        }
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    init(typeOfButton: TypeOfButton, title: String? = nil, target: AnyObject?, action: Selector) {
        super.init()
        self.typeOfButton = typeOfButton
        setup()
        self.target = target
        self.action = action
        self.title  = title
    }

    override func setup() {
        //same for all
        setTitleTextAttributes([NSAttributedStringKey.font : UIFont.defaultFont(size: 15)],for: UIControlState.normal)
        //depending on the type
        switch typeOfButton {
        case .cancel  :
            title = nil
            image = PaintCode.imageOfBarbtn_cancel(language: currentVisibleLanguage)
        case .ok      :
            title = nil
            image = PaintCode.imageOfBarbtn_ok(language: currentVisibleLanguage)
        case .done    :
            title = nil
            image = PaintCode.imageOfBarbtn_done(language: currentVisibleLanguage)
        case .edit    :
            title = nil
            image = PaintCode.imageOfBarbtn_edit(language: currentVisibleLanguage)
        case .uninitializedLoadedFromStoryboard :
            title = nil
            image = PaintCode.imageOfBarbtn_unknown
            break
        case .unknown:
            log.error("BarBtnPaintCode used with unrecognized type")
            title = nil
            image = PaintCode.imageOfBarbtn_unknown
            break
        }

    }

}
1
  • Fantastic solution, implemented with Swift 4 no problems. if you use this be careful of spelling types correctly in storyboards and xibs Dec 13, 2018 at 10:24
1

As @sikhapol answered, this is not possible. The workaround I use for this is to have a bunch of IBInspectable bools in my class and just select one in interface builder. For added security that multiple ones are not set, add an NSAssert in the setter for each one.

- (void)setSomeBool:(BOOL)flag
{
    if (flag)
    {
        NSAssert(!_someOtherFlag && !_someThirdFlag, @"Only one flag can be set");
    }
}

This is a little tedious and a bit sloppy IMO, but it's the only way to accomplish this kind of behavior that I can think of

1

I want to add that the identifiers of an enum are not available at runtime for anybody in Objective-C. So there cannot be a possibility to display it anywhere.

1

My solution was to do :

@IBInspectable  
var keyboardType = UIKeyboardType.default.rawValue {
        didSet { 
             textField.keyboardType = UIKeyboardType(rawValue: keyboardType)! 
        }
}

On the IB itself, you will need to set an int in the keyboardType field

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.