You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI TextField(.url格式)合法URL返回nil问题排查

概述

存在一个接收URL的文本框,若URL合法则需将其赋值给变量url

实现方式
  • 使用TextField("URL", value: $url, format: .url, prompt: Text("URL"))时,合法URL https://www.apple.com 返回nil
问题1
  1. 在URL输入框中输入https://www.apple.com
  2. 点击姓名输入框
  3. 发现URL输入框变为空(值为nil)
问题2
  1. 在URL输入框中输入https://www.apple.com
  2. 点击保存按钮
  3. 发现打印出的URL为nil
测试观察结果

点击保存按钮时

  • 异常情况:输入https://www.apple.com时,打印url = nil
  • 正常情况:输入https://www.apple.com/a时,打印url = https://www.apple.com/a

点击姓名输入框时

  • 异常情况:输入https://www.apple.com,URL输入框变为空
  • 异常情况:输入https://www.apple.com/,URL输入框变为空
  • 正常情况:输入https://www.apple.com/a,URL输入框保留原输入内容
代码
struct ContentView: View {
    @State private var url: URL?
    @State private var name = ""
    var body: some View {
        VStack {
            TextField("URL", value: $url, format: .url, prompt: Text("URL"))
                .keyboardType(.URL)
            TextField("Name", text: $name, prompt: Text("Name"))
            Button("save") {
                if let url {
                    print("url = \(url)")
                } else {
                    print("url is nil")
                }
            }
        }
    }
}

内容的提问来源于stack exchange,提问作者user1046037

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 06:37:30