2017-03-04 37 views
0

我有下面的代碼工作確定:NSAlert - 我該如何呈現一張視圖並在Swift3中獲取返回值?

func alertDialog(question: String, text: String) -> Bool { 
    let alert: NSAlert = NSAlert() 
    alert.messageText = question 
    alert.informativeText = text 
    alert.alertStyle = NSAlertStyle.warning 
    alert.addButton(withTitle: "Yes Please") 
    alert.addButton(withTitle: "No Thank You") 
    changedItem = false 
    return alert.runModal() == NSAlertFirstButtonReturn 

我檢查NSAlertFirstButtonReturn這樣的值:

func tableViewSelectionDidChange(_ notification: Notification) 
    { 
     print (#function, "changedItem", changedItem!) 
     if changedItem == true { 
      let answer = alertDialog(question: "Save your changes?", text: "Unsaved changes will be shredded.") 
      print(#function, "answer: ", answer) 
      if answer == true { 
       print(#function, "TRUE") 
       saveChanges(self) 
       changedItem = false 
      } 
     } 

我掙扎,執行相同的功能,但顯示警告如紙。

我不知道如何呈現和測試結果。我目前正在全部真實或全部虛假。

我已經嘗試了各種排列,如以下沒有喜悅,並會感謝任何幫助。

//instead of the return sheetModal 

     var result: Int! = 0 
     //result = false 
     alert.beginSheetModal(for: self.view.window!, completionHandler: { (NSAlertFirstButtonReturn) -> Void in 
      if NSAlertFirstButtonReturn.hashValue == 1000 { 
       result = 1 
      } else { 
       result = 0 
      } 


     }) 
     print(#function, "NSAlertFirstButtonReturn: ", NSAlertFirstButtonReturn.hashValue) 
     changedItem = false 

     if result == 1 { 
      return true 
     } else { 
      return false 
     } 

回答

1

不像runModal方法beginSheetModal(for:completionHandler:)以異步方式工作。從包含異步任務的函數/方法返回值是不可能的。

添加完成處理的方法alertDialog

func alertDialog(question: String, text: String, completion: @escaping (Bool)->()) { 
    let alert: NSAlert = NSAlert() 
    alert.messageText = question 
    alert.informativeText = text 
    alert.alertStyle = NSAlertStyle.warning 
    alert.addButton(withTitle: "Yes Please") 
    alert.addButton(withTitle: "No Thank You") 
    changedItem = false 
    alert.beginSheetModal(for: self.view.window!, completionHandler: { result in 
     completion(result == NSAlertFirstButtonReturn) 
    }) 
} 

和使用方法:

func tableViewSelectionDidChange(_ notification: Notification) 
{ 
    print (#function, "changedItem", changedItem!) 
    if changedItem == true { 
     alertDialog(question: "Save your changes?", text: "Unsaved changes will be shredded.", completion: { [unowned self] answer in 
      print(#function, "answer: ", answer) 
      if answer == true { 
       print(#function, "TRUE") 
       self.saveChanges(self) 
       self.changedItem = false 
      } 
     }) 
    } 
} 

的功能幾乎是相同的,但執行是異步的。

附註:爲什麼changedItem是可選的?這似乎是一個真正的Bool只與兩個狀態。

+0

改變項目的好處。我也很感謝你的深入解答。即將試用 –

+0

完美。非常感謝 –

相關問題