SwiftUI—使用TextField文本输入框接收用户的数据

原文链接:https://github.com/fzhlee/SwiftUI-Guide#8TextField

TextField类似于UIKit中的UITextField,用于实现用户的文字内容的输入。
示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
struct ContentView : View {
   
    @State var username : String //用于接收用户在TextField中输入的内容,并在左侧添加@state关键词
//@State是指属性代理,它表示username属性将和界面上的元素进行绑定。当属性的值发生变化时,SwiftUI会立即通知绑定的视觉元素进行内容的更新
    @State var nickname : String
   
    var body: some View {
       
        VStack{
           
            Text("Your username is \(username)!") //由于username属性拥有@State标记,所以一旦username属性的值发生变化,文本视图上的文字内容也会立即刷新
           
            Text("Your nickname is \(nickname)!")
           
            TextField("User Name", text: $username, onEditingChanged: { (value) in //设置text属性为username的值,$是指Binding wrapper绑定包装,表示可以修改属性的值
                print("onEditingChanged:\(self.username)") //当用户修改文本输入框里的内容时,在控制台输出属性的值,实时观察属性的值的变化
            }) {
                print("onCommit:\(self.username)") //当用户完成文本框里的输入时,在控制台输出username属性的值
            }.textFieldStyle(RoundedBorderTextFieldStyle()) //设置TextField的样式为圆角边框样式
           
            TextField("Nick Name", text: $nickname)
                .textFieldStyle(RoundedBorderTextFieldStyle())
           
        }
        .padding()
        //只有实时预览模式才可以和界面中的元素进行交互
    } //通过绑定包装特性,即可实现界面元素和数据内容的实时绑定
}

#if DEBUG
struct ContentView_Previews : PreviewProvider {
   
    static var previews: some View {
        ContentView(username: "", nickname: "") //由于给ContentView结构体添加了两个属性,所以需要更新PreviewProvider的属性的值,这样才可以在右侧的预览窗口显示正确的内容
    }
}
#endif

SceneDelegate.swift:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?


    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).

        // Create the SwiftUI view that provides the window contents.
        let contentView = ContentView(username: "", nickname: "") //由于ContentView新增了两个属性,所以需要修改此处的初始化方法。

        // Use a UIHostingController as window root view controller.
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: contentView)
            self.window = window
            window.makeKeyAndVisible()
        }
    }

    func sceneDidDisconnect(_ scene: UIScene) {
        // Called as the scene is being released by the system.
        // This occurs shortly after the scene enters the background, or when its session is discarded.
        // Release any resources associated with this scene that can be re-created the next time the scene connects.
        // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
    }

    func sceneDidBecomeActive(_ scene: UIScene) {
        // Called when the scene has moved from an inactive state to an active state.
        // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
    }

    func sceneWillResignActive(_ scene: UIScene) {
        // Called when the scene will move from an active state to an inactive state.
        // This may occur due to temporary interruptions (ex. an incoming phone call).
    }

    func sceneWillEnterForeground(_ scene: UIScene) {
        // Called as the scene transitions from the background to the foreground.
        // Use this method to undo the changes made on entering the background.
    }

    func sceneDidEnterBackground(_ scene: UIScene) {
        // Called as the scene transitions from the foreground to the background.
        // Use this method to save data, release shared resources, and store enough scene-specific state information
        // to restore the scene back to its current state.
    }


}