在Swift 3中使用Selector

编程入门 行业动态 更新时间:2024-10-26 08:31:41
本文介绍了在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

本文发布于:2023-11-26 21:58:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635358.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Swift   Selector

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!