Search code examples
swiftxcodemacosnsalert

NSAlert - Added Buttons not appearing in the correct Order


I'm trying to create an NSAlert with 2 buttons.

    let a = NSAlert()
    a.messageText = "Do you want go to A or B?"            
    a.alertStyle = .informational
    a.addButton(withTitle: "Yes")
    a.addButton(withTitle: "No")
    a.beginSheetModal(for: self.view.window!, completionHandler: { (modalResponse) -> Void in
    if modalResponse == NSAlertFirstButtonReturn { // do stuff}

Problem is that the Button No Appers before Yes and the second button appears to be preselected.Why is this happening?

I need the buttons to appear in the order in which they are added and no button preselected.


Solution

    • Fix order by adding first "No" button then add "Yes"
    • Disable preselection by setting keyEquivalent to ""

      let alert = NSAlert()
      alert.messageText = "Do you want go to A or B?"
      alert.alertStyle = .informational
      alert.addButton(withTitle: "No")
      alert.addButton(withTitle: "Yes")
      alert.buttons[0].keyEquivalent = ""
      ...
      

    enter image description here