本文介绍了在Swift 3中使用Selector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Swift 3中编写我的iOS应用程序。
I am writing my iOS Application in Swift 3.
我有一个 UIViewController 扩展,我有检查控制器实例是否响应方法。下面是我尝试的代码。
I have a UIViewController extension, where I have to check if the controller instance responds to a method. Below is the code that I a trying out.
extension UIViewController { func myMethod() { if self.responds(to: #selector(someMethod)) { } }}这里响应(to:)方法抛出编译时错误
Here the responds(to:) method throws a compile time error
使用未解析的标识符someMethod。
Use of unresolved identifier "someMethod".
我在另一篇文章中读到,我们必须在选择器内使用 self 参数,但即使这会引发一些错误。
I read in another post, we have to use self inside the selector argument, but even that is throwing some error.
推荐答案一个简单的解决方法:
@objc protocol SomeMethodType { func someMethod() } extension UIViewController { func myMethod() { if self.responds(to: #selector(SomeMethodType.someMethod)) { //... self.perform(#selector(SomeMethodType.someMethod)) // or (self as AnyObject).someMethod?() //... } } }
多一点Swifty方式:
A little more Swifty way:
protocol SomeMethodType { func someMethod() } //For all classes implementing `someMethod()`. extension MyViewController: SomeMethodType {} //... extension UIViewController { func myMethod() { if let someMethodSelf = self as? SomeMethodType { //... someMethodSelf.someMethod() //... } } }更多推荐
在Swift 3中使用Selector
发布评论