生成警报视图时出现此错误“尝试显示其视图不在窗口层次结构中!”。 请看下面的代码。我正在使用操作队列来执行警报任务。
class AlertOperation: ASOperation {
// MARK: Properties
fileprivate let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .alert)
fileprivate let presentationContext: UIViewController?
var title: String? {
get {
return alertController.title
}
set {
alertController.title = newValue
name = newValue
}
}
var message: String? {
get {
return alertController.message
}
set {
alertController.message = newValue
}
}
// MARK: Initialization
init(presentationContext: UIViewController? = nil) {
self.presentationContext = presentationContext ?? UIApplication.shared.keyWindow?.rootViewController
super.init()
addCondition(AlertPresentation())
/*
This operation modifies the view controller hierarchy.
Doing this while other such operations are executing can lead to
inconsistencies in UIKit. So, let's make them mutally exclusive.
*/
addCondition(MutuallyExclusive<UIViewController>())
}
func addAction(_ title: String, style: UIAlertActionStyle = .default, handler: @escaping (AlertOperation) -> Void = { _ in }) {
let action = UIAlertAction(title: title, style: style) { [weak self] _ in
if let strongSelf = self {
handler(strongSelf)
}
self?.finish()
}
alertController.addAction(action)
}
override func execute() {
guard let presentationContext = presentationContext else {
finish()
return
}
DispatchQueue.main.async {
if self.alertController.actions.isEmpty {
self.addAction("OK")
}
presentationContext.present(self.alertController, animated: true, completion: nil)
}
}
}
这是第一次工作正常,但如果我按警告上的取消按钮比它给我上面的错误。目前,如果用户按下取消按钮,我将从同一功能打开另一个警报。
final func finish(_ errors: [NSError] = []) {
if !hasFinishedAlready {
hasFinishedAlready = true
state = .finishing
let combinedErrors = _internalErrors + errors
finished(combinedErrors)
for observer in observers {
observer.operationDidFinish(self, errors: combinedErrors)
}
state = .finished
}
}
答案 0 :(得分:0)
检查presentationContext
是否存在问题,即窗口层次结构中是否存在其视图,
为此尝试替换
presentationContext.present(self.alertController, animated: true, completion: nil)
带
UIApplication.shared.keyWindow?.rootViewController?.present(self.alertController, animated: true, completion: nil)
如果能够在window's
rootViewController
上展示,请尝试解析presentationContext
。