SwiftUI Textfield Alert for macOS

Is it possible (also with detours via AppKit) to create text field alerts for macOS in SwiftUI? I found several tutorials on how to do that with UIKit for iOS but you can't use these solutions for macOS.

Post not yet marked as solved Up vote post of SwiftUserI Down vote post of SwiftUserI
81 views

Accepted Reply

macOS 13 Beta Release Notes

SwiftUI

New Features

• You can now place a TextField in an Alert by using alert modifiers that accept a ViewBuilder . (64819930)

I haven't tested it yet as I'm still using Monterey, but it should work according to the release notes.

If you are looking for macOS 12 and earlier solutions, you can do something like this:

Button("Tap Me") {
    let alert = NSAlert()
    alert.messageText = "Alert with text field"
    alert.addButton(withTitle: "OK")

    // You can customise this text field, this is just an example.
    alert.accessoryView = NSTextField(string: "Text")
            
    alert.runModal()
}
  • Thank you, you saved my life!

Add a Comment

Replies

macOS 13 Beta Release Notes

SwiftUI

New Features

• You can now place a TextField in an Alert by using alert modifiers that accept a ViewBuilder . (64819930)

I haven't tested it yet as I'm still using Monterey, but it should work according to the release notes.

If you are looking for macOS 12 and earlier solutions, you can do something like this:

Button("Tap Me") {
    let alert = NSAlert()
    alert.messageText = "Alert with text field"
    alert.addButton(withTitle: "OK")

    // You can customise this text field, this is just an example.
    alert.accessoryView = NSTextField(string: "Text")
            
    alert.runModal()
}
  • Thank you, you saved my life!

Add a Comment