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

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

本文介绍了Swift编写一个以self作为输入的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有来自不同位置的警报,所以我决定调用一个函数。

I have alert that is being fired from different location so I decided to make a function to be called.

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)
}

问题是,自我显然不是普遍的,我无法弄清楚如何通过它。有没有办法通过自我或更好的方式来解决整体问题?

The problem is that the self obviously isn't universal and I'm having trouble figuring out how to pass it. Is there a way to pass self or better yet a superior way to approach the problem overall?

推荐答案

你需要的是扩展UIViewController这种方式你不需要传递任何视图控制器作为参数,而self将始终是一个视图控制器。并确保调用视图控制器的当前方法 present(_ viewControllerToPresent:UIViewController,动画标志:Bool,完成:(() - > Void)?= nil)来自主线程:

What you need is to extend UIViewController this way you don't need to pass any view controller as parameter and self will always be a view controller. And make sure you call the view controller's present method present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) from the main thread:

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)
        }
    }
}






用法:


Usage:

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

这篇关于Swift编写一个以self作为输入的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 11:27