带有Swift枚举的Xcode 6运行时属性

带有Swift枚举的Xcode 6运行时属性,xcode,swift,Xcode,Swift,我在Swift上有一门课叫做按钮: enum ButtonBackgroundColor { case None case Yellow } class Button: UIButton { var backgroundColorType: ButtonBackgroundColor? } 然后我设置一个运行时属性: 然而,我得到了一个非描述性的崩溃。堆栈跟踪提到了一些关于键值编码的内容 但是,运行时属性对非枚举类型(如Int或Float)有效: // runtim

我在Swift上有一门课叫做
按钮

enum ButtonBackgroundColor {
    case None
    case Yellow
}

class Button: UIButton {
    var backgroundColorType: ButtonBackgroundColor?
}
然后我设置一个运行时属性:

然而,我得到了一个非描述性的崩溃。堆栈跟踪提到了一些关于键值编码的内容

但是,运行时属性对非枚举类型(如Int或Float)有效:

// runtime attributes work for this
var backgroundColorType: Int = 0

我声明枚举的方式有问题吗?

鉴于您的枚举
按钮BackgroundColor
包含
.None
案例,为什么不避免将
按钮中的
backgroundColorType
声明为可选?这样做毫无必要地使宣言复杂化。偏爱

class Button: UIButton {
  var backgroundColorType = ButtonBackgroundColor.None
}
除了在习惯用法上更为正确之外,上面的内容还可以解决“用户定义属性”的问题,因为变量不是可选的

您可能还需要在枚举中提供原始值。比如:

enum ButtonBackgroundColor : Int {
  case None = 0
  case Yellow = 1
}

如果您希望运行时属性值“0”可能映射到
。无

@GoZoner的答案对我不起作用。尝试将原始类型更改为
String
,但效果不佳。我的解决方案是定义另一个变量(运行时属性支持的任何类型),然后覆盖该变量的
didSet
,以设置枚举

因此,在代码中:

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

我不喜欢重复开关/案例中的内容,但我现在想不出更好的解决方案。

您已在Interface Builder中将对象设置为您的
按钮类,对吗?这仍然不起作用。另外,除非您的枚举声明为类似
enum按钮backgroundColor:NSInteger
谢谢,否则您不能执行
case None=0
;更新为添加“:Int”-只是希望帮助您将某个UI设计窗口中的
0
映射到您的枚举…您可以将
enum
的原始值设置为
String
,值为
“None”
“Yellow”
。。。如果返回
nil
,则使用原始值的初始值设定项并使用
。无
。@MarcoBoschi是的,我也尝试过。但由于某种原因,当它是运行时用户定义的时,它不会。我得到键值编码错误