【问题标题】:How to make a method available in the whole project如何使方法在整个项目中可用
【发布时间】:2016-03-06 13:57:28
【问题描述】:

我有以下代码来处理滑动手势。

    func handleSwipes(sender:UISwipeGestureRecognizer) {

    if (sender.direction == .Right) {
        print("Swipe Right")
        self.performSegueWithIdentifier("eventsModally", sender: self)
    }
}

让这个方法在整个项目中可用而不是在每个 ViewController 类中实现它的最佳实践是什么?

非常感谢您的帮助。

【问题讨论】:

    标签: ios swift extension-methods


    【解决方案1】:

    把它放在class extension.

    extension UIViewController {
        func handleSwipes(sender:UISwipeGestureRecognizer) {
            if (sender.direction == .Right) {
                print("Swipe Right")
                self.performSegueWithIdentifier("eventsModally", sender: self)
            }
        }
    }
    

    【讨论】:

    • 完美运行。是否有另一种方法,允许我在每个控制器中使用它,即使不是每个控制器都是 UIViewController? f.e. UITableViewController?
    • UITableViewController 是一个 UIViewController,所以UIViewController上的这个扩展应该适用于任何继承自UIViewController的类——包括UITableViewController
    • 好吧不知道。感谢您的努力。
    • 能否请您编辑您的答案并告诉我如何使 segue "eventsModally" 通用?
    • 我用:let rightSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipes:")) 调用函数,但我不知道如何给它一个字符串作为 segue 名称。
    猜你喜欢
    • 2020-08-07
    • 2012-06-04
    • 2016-07-02
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    • 2021-09-25
    • 1970-01-01
    • 2021-01-15
    相关资源
    最近更新 更多