Mad*_*tha 2 iphone ios swift uialertcontroller
我想为我的项目创建一个可重用的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)
}
}
Run Code Online (Sandbox Code Playgroud)
我在另一个视图控制器中调用它
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.
}
}
Run Code Online (Sandbox Code Playgroud)
你可以使用Anbu Karthiks的答案.作为替代方案,我使用Swift 2s协议扩展来显示警报.
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)
}
}
Run Code Online (Sandbox Code Playgroud)
现在,在您需要显示警报的viewControllers中,您只需遵守协议即可
class ViewController: UIViewController, Alertable { }
Run Code Online (Sandbox Code Playgroud)
并调用方法
showAlert(title: "Alert title", message: "Alert message")
Run Code Online (Sandbox Code Playgroud)
好像它们是viewController本身的一部分.
Swift SpriteKit:在GameScene中访问UIViewController的最佳实践
注意:正如成员在评论中所说,viewDidLoad可能会很快显示警告.尝试稍微延迟或使用ViewDidAppear
希望这可以帮助
| 归档时间: |
|
| 查看次数: |
2518 次 |
| 最近记录: |