UIControlState.Normal 不可用

UIControlState.Normal is Unavailable

以前对于 UIButton 个实例,您可以为 setTitlesetImage 传入 UIControlState.Normal.Normal 不再可用,我应该用什么代替?

let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
btn.setTitle("title", for: .Normal) // does not compile

(这是一个规范的问答对,以防止与 UIButtonUIControl 相关的重复问题泛滥 iOS 10 和 Swift 3)

Swift 3 次更新:

似乎 Xcode 8/Swift 3 带回了 UIControlState.normal:

public struct UIControlState : OptionSet {

    public init(rawValue: UInt)


    public static var normal: UIControlState { get }

    public static var highlighted: UIControlState { get } // used when UIControl isHighlighted is set

    public static var disabled: UIControlState { get }

    public static var selected: UIControlState { get } // flag usable by app (see below)

    @available(iOS 9.0, *)
    public static var focused: UIControlState { get } // Applicable only when the screen supports focus

    public static var application: UIControlState { get } // additional flags available for application use

    public static var reserved: UIControlState { get } // flags reserved for internal framework use
}

UIControlState.Normal 已重命名为 UIControlState.normal 并从 iOS SDK 中删除。对于 "Normal" 个选项,使用空数组构造一个空选项集。

let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 20, height: 20))

// Does not work
btn.setTitle("title", for: .Normal) // 'Normal' has been renamed to 'normal'
btn.setTitle("title", for: .normal) // 'normal' is unavailable: use [] to construct an empty option set

// Works
btn.setTitle("title", for: [])

删除了.Normal(iOS 10 DP1),如果你没有,可以用[]UIControlState(rawValue: UInt(0))代替.Normal不想更改所有代码(以防苹果再次添加它或者您不喜欢[]),您可以只添加一次此代码

extension UIControlState {
    public static var Normal: UIControlState { return [] }
}

extension UIControlState {
    public static var Normal: UIControlState { return UIControlState(rawValue: UInt(0)) }
}

然后所有 .Normal 都像以前一样工作。

Apple 在更新的 Xcode beta 版本中恢复了正常的控制状态。升级到最新的 Xcode 测试版并使用 .normal.

Swift 5

替换自

btn.setTitle("title", for: .Normal)

btn.setTitle("title", for: UIControl.State.normal)