Pesquisar

segunda-feira, 3 de setembro de 2018

Why I can’t use IBInspectable with enumeration?

I remember when I saw the WWDC in 2014 about the IBInspectable and IBDesignable, my reaction was:



It was amazing, now I can create a component and see the result inside of Interface Builder and I can configure it, this is a great feature that designer can use it. Perfect! not.


For understanding about the IBDesignable and IBInspectable, see my other article about this - What’s IBDesignable / IBInspectable?.

Trying to use enum with IBInspectable

If you try to create an enum like the code bellow and use it with the IBInspectable property, you’ll see that not works.


IBInspectable works with a little bit limitation about the types: Int, CGFloat, Double, String, Bool, CGPoint, CGSize, CGRect, UIColor, and UIImage.

I think that IBInspectable can not support an enum because as the Swift Programming Language says:

"Use enum to create an enumeration. Like classes and all other named types, enumerations can have methods associated with them." [1]

So enum is not only a simple enumeration, you can create much more for (e.g.):



My solution to use IBInspectable with enum

Unfortunately, to resolve this problem I need to change my code and I used a boolean value:



Ok! With this solution I have only two cases and no more Medium case, I removed it because it was not a problem for user experience. I think that is better than put the fullFormat with another type like Int or String… Why?

Another solutions

If you put in your code an IBInspectable property with Int type, the user of Interface Builder needs to know the range values of your enumeration and you need to set the format value when the fullFormat value is outside of range (e.g.):



Short case

Full case

Int case is similar to String or another type…

References

[1] Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/br/jEUH0.l