14

以前对于UIButton实例,您可以传入UIControlState.NormalforsetTitlesetImage.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 的变化而发生变化)

4

4 回答 4

22

斯威夫特 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 中删除。对于“正常”选项,使用一个空数组来构造一个空选项集。

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: [])
于 2016-06-13T22:47:20.060 回答
2

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

于 2016-06-22T21:23:05.067 回答
2

.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工作。

于 2016-06-14T06:51:00.997 回答
1

斯威夫特 5

替换自

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

btn.setTitle("title", for: UIControl.State.normal)
于 2019-07-24T10:36:28.427 回答