使用Swift将常用方法放在单独的文件中

arp*_*rpo 1 ios swift

我喜欢将常用的方法放在一个单独的文件中.我发现这个答案使用Swift中另一个类中的一个类的函数,但是我按照我想要的方式使用它会出错.

假设我想创建一个名为msgBox的方法,弹出一个警告框.我创建了一个单独的空Swift文件并将此代码放入其中.

import UIKit

class Utils: UIViewController {

    class func msgBox (titleStr:String = "Untitled", messageStr:String = "Alert text", buttonStr:String = "Ok") {
        var alert = UIAlertController(title: titleStr, message: messageStr, preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: buttonStr, style: .Default, handler: { (action) -> Void in
            self.dismissViewControllerAnimated(true, completion: nil)
        }))
        self.presentViewController(alert, animated: true, completion: nil)
    }

}
Run Code Online (Sandbox Code Playgroud)

我想这样称呼它,但我这样做会出错.有谁知道我做错了什么?

Utils.msgBox(titleStr: "Hello!", messageStr: "Are you sure?")
Run Code Online (Sandbox Code Playgroud)

错误如下所示: 在此输入图像描述

Eri*_*ric 5

这个错误是因为你使用selfclass方法.self在这种情况下,没有实例.

在这种情况下你可以做的一件事就是进行类扩展.在以下示例中,您可以alert从任何UIViewController实例调用该方法:

extension UIViewController {

    func alert(title: String?, message: String?, buttonTitle: String = "OK") {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
        alert.addAction(UIAlertAction(title: buttonTitle, style: .Default, handler: { action in
            self.dismissViewControllerAnimated(true, completion: nil)
        }))
        self.presentViewController(alert, animated: true, completion: nil)
    }

}
Run Code Online (Sandbox Code Playgroud)

请注意,我更改了几个名称和类型,但您可以使用您喜欢的.