Swift Enum to Cocoa Touch UIButton 选择器字符串

标签 swift enums uibutton selector addtarget

我正在为我的 letterTapped() 函数向 UIButton 添加一个目标,如下所示:

button.addTarget(self, action: "letterTapped:", forControlEvents: .TouchUpInside)

我喜欢 .TouchUpInside 如何与自动完成一起工作,它看起来比我应该用于 action: 参数的字符串更整洁、更安全。所以我搜索并找到了this tutorial它使用枚举来替换“魔术字符串”。

我创建了一个这样的枚举:

    enum functionForAction: Selector {

    case clearTapped = "clearTapped:"
    case submitTapped = "submitTapped:"
    case letterTapped = "letterTapped:"

}

然后我这样使用它:

 button.addTarget(self, action: functionForAction.letterTapped.rawValue, forControlEvents: .TouchUpInside)

我获得了代码补全,而且我从不尝试调用拼写错误的选择器。感觉好多了。但是有可能改进吗?我真的只想输入:

 button.addTarget(self, action: .letterTapped, forControlEvents: .TouchUpInside)

枚举能否在 Swift 中为我实现这一点?

最佳答案

有两种方法可以做到这一点,虽然可以得到您想要的语法,但我认为第二种方法很可能是更好的方法。

为了做你想做的事,我们将像你一样创建一个枚举,但也会向 UIControl(UIButton 的父类(super class))添加一个扩展,这样我们就可以使用 ControlSelector

添加目标
enum ControlSelector: Selector {
    case ClearTapped = "clearTapped:"
    case SubmitTapped = "submitTapped:"
    case LetterTapped = "letterTapped:"
}

extension UIControl {
    func addTarget(target: AnyObject?, action: ControlSelector, forControlEvents controlEvents: UIControlEvents) {
        addTarget(target, action: action.rawValue, forControlEvents: controlEvents)
    }
}

现在我们可以使用您喜欢的语法调用 addTarget:

button.addTarget(self, action: .ClearTapped, forControlEvents: .TouchUpInside)

(顺便说一下,按照惯例,枚举的第一个字母通常是大写字母,这就是为什么我从你的代码中稍微改变了它。)

但是,这可能会变得困惑,除非您希望您的 ControlSelector 枚举在所有代码之间共享(现在,让选择器更清晰有什么意义)?要在您的所有代码中实现这一点,您要么必须将两者的访问级别保持为公开,要么在您希望以这种方式编写内容的每个文件中编写 UIControl 扩展。

我建议改为使用私有(private)类来保持选择器清晰。

private class ControlSelector {
    static var clearTapped: Selector = "clearTapped:"
    static var submitTapped: Selector = "submitTapped:"
    static var letterTapped: Selector = "letterTapped:"
}

然后您将不再需要协议(protocol)扩展,而是以这种方式调用您的 addTarget 方法:

button.addTarget(self, action: ControlSelector.clearTapped, forControlEvents: .TouchUpInside)

希望这对您有所帮助!

关于Swift Enum to Cocoa Touch UIButton 选择器字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35248796/

相关文章:

ios - 加速度计失灵了

c# - 使用 EnumToList<T> 时如何将 <T> 转换为 Enum

c++ - 将 c 枚举导入到 c++ 类定义

ios - 将 2 行属性字符串添加到 UIButton 的标题不起作用

ios - UIButton 标题文本颜色

ios - 初始化变量 : 'self' captured by a closure before all members were initialized

swift - UIImageView 不显示通过 UIIMagePickerController 选择的图像

ios - 是否可以更改具有不同类的对象的类类型?

ios - 为什么当我添加注释时我的 map View 会放大?

ios - Swift:使用闭包的枚举?