带有适用于 iOS 13 及更高版本文本字段的 SwiftUI 警报

TextFieldAlert

带有适用于 iOS 13 及更高版本的文本字段的 SwiftUI 警报。

由于Apple将在iOS 16中引入文本字段作为警报操作,因此这是旧版本的良好替代品。

要求

  • iOS 13.0+
  • 斯威夫特 5.1+

Installation

You can add TextFieldAlert to an Xcode project by adding it as a package dependency.

  1. From the File menu, select Add Packages…
  2. Enter into the package repository URL text field.https://github.com/sochalewski/TextFieldAlert
  3. Add the package to your app target.

Usage

TextFieldAlert is exposed through extension:View

func textFieldAlert(
    title: String?,
    message: String?,
    textFields: [TextFieldAlert.TextField],
    actions: [TextFieldAlert.Action],
    isPresented: Binding<Bool>
)

You can use it in your code as follows:

struct ExampleView: View {
    
    @State var isPresented = false
    @State var text1 = ""
    @State 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
        )
    }
}

More advanced usage (incl. moving the responsibility to a view model, some customization and enabling action buttons conditionally) is available in the Example app.

Author

Piotr Sochalewski, sochalewski.github.io

TextFieldAlert is heavily inspired by tanzolone‘s answer on StackOverflow.

License

TextFieldAlert is available under the MIT license. See the LICENSE file for more info.

GitHub

点击跳转