繁体   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