Swift编写一个以self作为输入的函数

时间:2017-11-08 22:30:05

标签: ios swift uialertcontroller

我有从不同位置被解雇的警报,因此我决定调用一个函数。

func alertSCFlag(x: Int) {
    var alert = UIAlertController()
    switch x {
    case 1:
        alert = UIAlertController(title: "Not Finished", message: "sorry but you must give the project a title and description", preferredStyle: UIAlertControllerStyle.alert)

    default:
        alert = UIAlertController(title: "Not Finished", message: "sorry but you need to choose a type of project", preferredStyle: UIAlertControllerStyle.alert)

    }
    alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
    self.present(alert, animated: true, completion: nil)
}

问题在于,自我显然不是普遍的,我在弄清楚如何通过它时遇到了麻烦。是否有办法通过自我或更好的方式来解决整体问题?

1 个答案:

答案 0 :(得分:1)

您需要的是以这种方式扩展UIViewController,您不需要将任何视图控制器作为参数传递,而self将始终是视图控制器。并确保从主线程中调用视图控制器的当前方法present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil)

extension UIViewController {
   enum Message: CustomStringConvertible  {
        case missingTitle, chooseProject
        var description: String {
            let message: String
            switch self {
            case .missingTitle: message = "sorry but you must give the project a title and description"
            case .chooseProject: message = "sorry but you need to choose a type of project"
            }
            return message
        }
    }
    func alertSCFlag(title: String = "Not Finished", message: Message) {
        let alert = UIAlertController(title: title, message: message.description, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .default))
        DispatchQueue.main.async {
            self.present(alert, animated: true)
        }
    }
}

用法:

let vc = UIViewController()
vc.alertSCFlag(message: .chooseProject)