Reputation: 32071
I have a class in Swift called Button
:
enum ButtonBackgroundColor {
case None
case Yellow
}
class Button: UIButton {
var backgroundColorType: ButtonBackgroundColor?
}
And then I'm setting a runtime attribute:
However, I get a non-descriptive crash. The stack trace mentions something about key value coding.
Runtime attributes do work however for non enum types, like Int or Float:
// runtime attributes work for this
var backgroundColorType: Int = 0
Is there something wrong with the way I'm declaring my enum?
Upvotes: 1
Views: 670
Reputation: 17834
@GoZoner's answer didn't work for me. Tried changing the raw type to String
and that didn't work as well. My solution is to define another variable (of whichever type supported by the runtime attributes) and then override the didSet
of that variable to set the enum.
So in code:
var IBButtonBackgroundColor = "None"
{
didSet
{
switch self.IBButtonBackgroundColor
{
case "None":
self.backgroundColorType = .None
break
case "Yellow":
self.backgroundColorType = .Yellow
break
default:
self.backgroundColorType = .None
break
}
}
}
var backgroundColorType:ButtonBackgroundColor = .None
I don't like having to repeat things in the switch/case, but I can't think of any better solution for now.
Upvotes: 0
Reputation: 70165
Given that your enum ButtonBackgroundColor
includes a .None
case, why not avoid declaring backgroundColorType
in Button
as an optional? Doing so needlessly complicates the declaration. Prefer
class Button: UIButton {
var backgroundColorType = ButtonBackgroundColor.None
}
Besides being more idiomatically correct, the above might, just might, fix your 'user defined attribute' issue now that the variable is not an optional.
You also might need to provide raw values in your enum. Like:
enum ButtonBackgroundColor : Int {
case None = 0
case Yellow = 1
}
if you expect the runtime attribute value of '0' to perhaps map to .None
Upvotes: 1