A SwiftUI alert with text fields for iOS 13+ and tvOS 13+.
On iOS 17 and later, TextFieldAlert uses the native SwiftUI alert implementation by default. On earlier iOS versions and tvOS, it uses a UIKit-backed implementation. Set alwaysPreferUIKit to true to use the UIKit implementation on iOS 17 and later as well.
- iOS 13.0+ or tvOS 13.0+
- Swift 5.1+
You can add TextFieldAlert to an Xcode project as a Swift package dependency.
- From the File menu, select Add Packages…
- Enter
https://github.com/sochalewski/TextFieldAlertin the package repository URL field. - Add the package to your app target.
The package adds textFieldAlert(...) to View:
@ViewBuilder
func textFieldAlert(
title: String?,
message: String? = nil,
textFields: [TextFieldAlert.TextField],
actions: [TextFieldAlert.Action],
isPresented: Binding<Bool>,
alwaysPreferUIKit: Bool = false
) -> some ViewYou can use it in your code as follows:
import SwiftUI
import TextFieldAlert
struct ExampleView: View {
@State private var isPresented = false
@State private var text1 = ""
@State private var text2 = ""
var body: some View {
VStack {
Button {
isPresented = true
} label: {
Text("Alert")
}
Text(text1)
Text(text2)
}
.textFieldAlert(
title: "Title",
message: "Message",
textFields: [
.init(text: $text1),
.init(text: $text2)
],
actions: [
.init(title: "OK")
],
isPresented: $isPresented
)
}
}Each action closure receives the current text values in the same order as the text fields passed to textFieldAlert. The Example app demonstrates advanced usage, including moving presentation state into a view model, customizing text fields, and enabling action buttons conditionally.
Piotr Sochalewski, sochalewski.github.io
TextFieldAlert is heavily inspired by tanzolone's answer on Stack Overflow.
TextFieldAlert is available under the MIT license. See the LICENSE file for more information.
