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

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

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


示例代码:


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:


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.
    }
}


2466108-a92a1ecb106ee677.webp.jpg


目录
相关文章
|
搜索推荐 数据管理 定位技术
iOS应用开发中有多种主流框架
iOS应用开发中有多种主流框架
769 60
SwiftUI—方便用户选择日期的DatePicker日期拾取器
SwiftUI—方便用户选择日期的DatePicker日期拾取器
1981 0
SwiftUI—方便用户选择日期的DatePicker日期拾取器
|
iOS开发
Xcode报错解决方法:ld: symbol(s) not found for architecture arm64
Xcode报错解决方法:ld: symbol(s) not found for architecture arm64
3866 0
|
5月前
|
Java 关系型数据库 数据库
深度剖析【Spring】事务:万字详解,彻底掌握传播机制与事务原理
在Java开发中,Spring框架通过事务管理机制,帮我们轻松实现了这种“承诺”。它不仅封装了底层复杂的事务控制逻辑(比如手动开启、提交、回滚事务),还提供了灵活的配置方式,让开发者能专注于业务逻辑,而不用纠结于事务细节。
|
开发者 人工智能 自然语言处理
欢迎使用通义灵码
灵码使用指南!一键收藏。
145342 31
|
10月前
|
存储 安全 生物认证
苹果上架APP遇到提示缺少出口合规证明时应该如何处理-什么是APP加密文稿-优雅草卓伊凡
苹果上架APP遇到提示缺少出口合规证明时应该如何处理-什么是APP加密文稿-优雅草卓伊凡
880 62
苹果上架APP遇到提示缺少出口合规证明时应该如何处理-什么是APP加密文稿-优雅草卓伊凡
|
Java 数据库连接 Spring
一文讲明 Spring 的使用 【全网超详细教程】
这篇文章是一份全面的Spring框架使用教程,涵盖了从基础的项目搭建、IOC和AOP概念的介绍,到Spring的依赖注入、动态代理、事务处理等高级主题,并通过代码示例和配置文件展示了如何在实际项目中应用Spring框架的各种功能。
一文讲明 Spring 的使用 【全网超详细教程】
|
存储 Swift
大师学SwiftUI第18章Part3 - 自定义视频播放器
录制和播放视频对用户来说和拍照、显示图片一样重要。和图片一样,Apple框架中内置了播放视频和创建自定义播放器的工具。
672 0
|
存储 JavaScript 前端开发
Axure设计之日期时间范围选择器
在产品设计和原型制作中,日期时间范围选择器是常见需求。本文介绍如何使用Axure的动态面板、中继器、文本框、按钮及时间函数,快速制作一个功能完备的日期时间范围选择器。详细步骤包括创建基本框架、设置时间函数、载入时获取当前时间、添加时间选择功能、更新文本框值和验证格式化。通过这些步骤,你可以在Axure中轻松实现这一功能。
1565 0
|
JSON 安全 前端开发
跨域请求出现preflight request失败的问题的解决
# 问题出现 这两天在项目联调过程中突然前端同学报告出现CORS跨域问题无法访问。刚听到很奇怪,因为已经在项目里面设置了CORS规则,理论上不会出现这个问题。 ```java protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
55031 1