在swift中相互重叠的多个警报

时间:2018-05-01 08:59:50

标签: swift alert uialertcontroller uialertaction

现在我收到错误: 警告:尝试在CollectionViewController上呈现UIAlertController:0x7f9af9016200:0x7f9af750d620已经呈现(null)

我可以在swift中堆叠警报吗? 有我的代码,如果项目超过前一天发布,它会显示警报。 有两种方法我试图这样做但没有成功。

  1. 暂停for循环直到我按是或否。
  2. 在彼此之上呈现许多提醒
  3. 任何解决方案如何设法做到这一点?

    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)
        }
    }
    

1 个答案:

答案 0 :(得分:2)

要在彼此之后显示警报,我建议添加此递归代码,

class添加messages变量,并为所有array条件填充true。之后,您必须调用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)
    }
}