ios - Objective-C 选择器弃用替换

标签 ios swift

正如最近许多问题所显示的那样,文字选择器已被弃用。有一个快速修复方法,如果选择器仅在该类中,则可以正常工作。

但是考虑这个例子(我有更多的代码;这是一个简化的例子):

static func createMenuButton(controller:UIViewController) -> UIBarButtonItem {
    let menuButton = UIButton(frame: CGRectMake(0, 0, 22, 22))
    menuButton.addTarget(controller, action: Selector("menuButtonClicked:"), forControlEvents:.TouchUpInside)
    let menuButtonContainer = UIView(frame: menuButton.frame)
    menuButtonContainer.addSubview(menuButton)
    let menuButtonItem = UIBarButtonItem(customView: menuButtonContainer)
    return menuButtonItem
}

这个实用方法为我提供了在各种 View Controller 中使用的良好功能。由于它有多种用途,我必须将它复制到每个 View Controller 才能使用新的 #selector 语法。但是 Apple,为什么要弃用更动态的方法呢?我想在新版本中他们会删除它,比如 i++i-- 和 C 风格的 for 循环(但它们可以是很容易更换,虽然我不明白他们为什么要删除它们)。是否有任何解决方法可以使这种方法在未来的版本中发挥作用?每个新版本都打破了我所有的项目语法。

最佳答案

why deprecate more dynamic method?

来自 the proposal to make this change :

we free the developer from having to do the naming translation manually and get static checking that the method exists and is exposed to Objective-C.

对于您的方法,您可以制定一个协议(protocol)来指示存在某种方法:

@objc protocol MenuButtonClickable {
    func menuButtonClicked()
}

在你的 View Controller 中,添加这个方法:

extension MyViewController : MenuButtonClickable {
    func menuButtonClicked() {
        // do something
    }
}

然后更新您的方法签名以使用此协议(protocol):

static func createMenuButton(controller:MenuButtonClickable) -> UIBarButtonItem {

现在 Swift 编译器保证 controller 有那个方法,所以你将能够使用新的 #selector 语法。

如果你不小心尝试在没有这个函数的 View Controller 上使用这个方法,你会得到一个编译时错误而不是运行时错误。

关于ios - Objective-C 选择器弃用替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36184626/

相关文章:

ios - 为什么在 SceneKit 着色器修改器中使用 glsl 或定义函数只会产生错误?

ios - Firebase Analytics 架构 x86_64 的 undefined symbol : "_OBJC_CLASS_$_FIRAnalytics"

swift - 带共享扩展的后台上传

swift - UILabel 不会随计时器更新

ios - 当我从主屏幕重新进入应用程序时是哪个阶段

ios - 未找到框架 GoogleMapsCore

ios - Swift 2 - AFNetwork 请求缓存问题

ios:在 iphone6 上运行时增加 UIViewController 中自定义 View 的宽度

ios - 如何使用 nsuserdefault 或 ios 中的任何其他对象保存动态添加的字段数据, objective-c

swift - 如何优雅地将 guard 语句与条件结合起来?