【问题标题】:.normal option doesn't work in state OptionSet for UIButton (Swift 3).normal 选项在 UIButton 的状态 OptionSet 中不起作用(Swift 3)
【发布时间】:2016-10-13 22:31:08
【问题描述】:

我正在尝试为 2 个UIButton 的状态设置相同的UIImage - 正常和突出显示

UIControlStateOptionSet,所以如果我传递一个数组,它应该工作。

myButton.setImage(UIImage(named: myButtonImageName), for: [.normal, .highlighted])

但上面的代码只设置了.highlighted状态而忽略了.normal(之前在IB中设置的图像仍然显示在.normal状态)

但是,如果我以 2 种方法运行它,它会起作用:

myButton.setImage(UIImage(named: myButtonImageName), for: .normal)
myButton.setImage(UIImage(named: myButtonImageName), for: .highlighted)

我错过了什么吗?

【问题讨论】:

    标签: ios swift uibutton uikit swift3


    【解决方案1】:

    在 Swift 中,OptionSet 的数组字面量表示一个按位或运算的值。

    UIControlState.normal.rawValue //->0
    UIControlState.highlighted.rawValue //->1
    

    因此:

    ([.normal, .highlighted] as UIControlState).rawValue //->1
    

    采用 OptionSet 类型并不意味着您总是可以将组合值传递给它。在您的情况下,您需要 as 2 方法

    【讨论】:

    • 您知道他们为什么将 0 值用于 OptionSet 吗?这对我来说没有任何意义...... AFAIK 大多数选项集变量都是单个位,如 1、2、4、8 等。所以你可以按位或。任何想法为什么 0 用于.normal
    猜你喜欢
    • 2018-01-13
    • 1970-01-01
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多