gpt4 book ai didi

ios - 如何创建可重用的 UIAlertcontroller?

转载 作者:可可西里 更新时间:2023-10-31 23:56:24 24 4
gpt4 key购买 nike

我想为我的项目创建一个可重用的 UIAlertController 类。我尝试了以下代码。但我的警报没有显示。我的代码或任何代码帮助有什么问题。这是我的警报类

class AlertView: NSObject {

class func showAlert(view: UIViewController , message: String){

let alert = UIAlertController(title: "Warning", message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
view.presentViewController(alert, animated: true, completion: nil)
}
}

我在我的另一个 View Controller 中调用它

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
AlertView.showAlert(self, message: "Test alert")
// Do any additional setup after loading the view, typically from a nib.
}
}

最佳答案

您可以使用 Anbu Karthiks 的答案。作为替代方案,我使用 Swift 2s 协议(protocol)扩展来显示警报。

import UIKit

protocol Alertable { }
extension Alertable where Self: UIViewController {

func showAlert(title title: String, message: String) {

let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)

let okAction = UIAlertAction(title: "OK", style: .Cancel) { _ in }
alertController.addAction(okAction)

DispatchQueue.main.async {
self.view?.window?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)
}
}

func showAlertWithSettings(title title: String, message: String) {

let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)

let okAction = UIAlertAction(title: "OK", style: .Cancel) { _ in }
alertController.addAction(okAction)

let settingsAction = UIAlertAction(title: "Settings", style: .Default) { _ in
guard let url = NSURL(string: UIApplicationOpenSettingsURLString) else { return }
UIApplication.sharedApplication().openURL(url)
}
alertController.addAction(settingsAction)

DispatchQueue.main.async {
self.view?.window?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)
}
}

现在在您需要显示警报的 viewController 中,您只需遵守协议(protocol)即可

class ViewController: UIViewController, Alertable { } 

然后像这样调用方法

showAlert(title: "Alert title", message: "Alert message")

好像它们是 viewController 本身的一部分。

Swift SpriteKit: Best practice to access UIViewController in GameScene

注意:正如成员在评论中所说,viewDidLoad 可能很快就会显示警报。尝试使用轻微的延迟或 ViewDidAppear

希望对你有帮助

关于ios - 如何创建可重用的 UIAlertcontroller?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37343355/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com