我是iOS开发的初学者。我正在尝试制作一个Swift文件,其中只包含一个显示警报的方法。该模型将用于某些视图控制器。
我制作一个Swift文件,发出警报的代码是这样的:
import UIKit
class Alert : UIAlertController {
func showAlert (alertTitle: String, alertMessage: String, actionTitle: String) {
let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
let alertAction1 = UIAlertAction(title: actionTitle, style: .default) { (action) in
}
alert.addAction(alertAction1)
present(alert, animated: true, completion: nil)
}
}
然后我在视图控制器中实现这个类
import UIKit
class ViewController: UIViewController {
var x = 10
var alert = Alert()
override func viewDidLoad() {
super.viewDidLoad()
if x < 15 {
test()
}
}
func test() {
alert.showAlert(alertTitle: "Opps", alertMessage: "less than 15", actionTitle: "OK")
}
}
但是我收到了一个错误:
警告:尝试出现&lt; UIAlertController:0x7fcc0bc05fc0&gt; on&lt; testAlert.Alert:0x7fcc0bc04bc0&gt;其视图不在窗口层次结构中!
我该怎么办?
答案 0 :(得分:1)
错误告诉所有内容:您正在创建Alert的实例,即UIAlertController,它正在创建另一个您想要在Alert实例上呈现的UIAlertController,它甚至不会由您的视图控制器呈现。
为什么不用该方法简单地为UIViewController创建扩展名?
请尝试以下操作:
extension UIViewController {
func showAlert(title: String, message: String, …) {
…
present(alert, animated: true, completion: nil)
}
}
您可以从任何UIViewController调用此方法,它将创建将从您的UIViewController呈现的UIAlertController:
// from your UIViewController code, for example from viewDidAppear method
self.showAlert(title: "Wow!", message: "It works!", actionTitle: "Dismiss")
答案 1 :(得分:1)
由于您的Alert
课程不是视图控制器,因此UIViewController
课程没有理由延长Alert
。
您应该做的是通过扩展程序将showAlert
方法设为UIViewController
方法。
变化:
class Alert : UIAlertController {
为:
extension UIAlertController {
然后,当您想要从视图控制器(例如ViewController
课程)显示提醒时,只需拨打showAlert
。
class ViewController: UIViewController {
func test() {
showAlert(alertTitle: "Opps", alertMessage: "less than 15", actionTitle: "OK")
}
}