我在產生警報視圖時出現此錯誤「嘗試在其視圖不在窗口層次中呈現!」。 請看下面我的代碼。我正在使用操作隊列來執行警報任務。UIAlertController在生成alertview時給出錯誤
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
}
}
你爲什麼需要手術?你也可以格式化你的代碼嗎?謝謝。 –
格式?,你的意思 –
我會爲你做。但下一次,請自己動手。 –