簡體   English   中英

多個警報彼此疊加

[英]Multiple alerts on top of each other in swift

現在我遇到錯誤:警告:嘗試在已經存在的CollectionViewController:0x7f9af750d620上呈現UIAlertController:0x7f9af9016200

有什么辦法可以迅速堆疊警報? 有我的代碼,如果項目發布超過一天,它會顯示警報。 我嘗試過兩種方法但未成功。

  1. 暫停for循環,直到我按“是”或“否”。
  2. 彼此呈現許多警報

任何解決方案如何設法做到這一點?

for p in json! {
     if self.checkDaysPassed(postDate: p["uploadedTime"] as! String) > 1 {
     print("more than one day passed, sell item?")

     let alert = UIAlertController(title: "Sell this item", message: "This item has been unused for a day", preferredStyle: .alert)
     alert.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
     alert.addAction(UIAlertAction(title: "Yes", style: .default){ (action) in
           print("pressed yes")
     })
     alert.addAction(UIAlertAction(title: "No", style: .cancel){ (action) in
          print("pressed no")
     })
     self.present(alert, animated: true)
    }
}

為了彼此顯示警報,我建議添加此遞歸代碼,

messages添加class變量,並為所有true條件填充array 之后,您只需要調用showAlert方法即可處理所有消息的顯示。

class YourClass {

   var messages: [String] = []


   func yourMethod() {
       for p in json! {
         if self.checkDaysPassed(postDate: p["uploadedTime"] as! String) > 1 {
             messages.append("This item has been unused for a day")
         }
       }
       self.showAlert()
   }

   private func showAlert() {
        guard self.messages.count > 0 else { return }

        let message = self.messages.first

        func removeAndShowNextMessage() {
            self.messages.removeFirst()
            self.showAlert()
        }

        let alert = UIAlertController(title: "Sell this item", message: message, preferredStyle: .alert)
        alert.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
        alert.addAction(UIAlertAction(title: "Yes", style: .default){ (action) in
            print("pressed yes")
            removeAndShowNextMessage()

        })
        alert.addAction(UIAlertAction(title: "No", style: .cancel){ (action) in
            print("pressed no")
            removeAndShowNextMessage()
        })

        UIApplication.shared.delegate?.window??.rootViewController?.present(alert, animated: true)
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM