【问题标题】:SwiftUI: How to block certain characters in a textfield?SwiftUI:如何阻止文本字段中的某些字符?
【发布时间】:2021-07-31 07:25:05
【问题描述】:

我的应用中有一个 url 地址栏,它只加载格式为“www.google.com”而不是“https://www.google.com”的网址

@State private var text = ""
@State private var site = "www.google.com/"

    TextField("Enter a URL", text: $text, onCommit: {
            guard !text.isEmpty else {return}
            site = text
        })

我希望文本字段屏蔽这些字符“https://”,这样每当用户从另一个浏览器复制和粘贴网址时,他们就不必每次都手动删除“https://”。

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

    你可以试试这样的:

        struct ContentView: View {
        @State var txt = ""
        
        var body: some View {
            TextField("Enter Url", text: Binding(
                get: { txt },
                set: { newValue in
                    if trim(newValue).starts(with: "https://") {
                        txt = String(trim(newValue).dropFirst(8))
                    } else {
                        txt = newValue
                    }
                }
            ))
        }
        
        func trim(_ str: String) -> String {
            return str.trimmingCharacters(in: .whitespacesAndNewlines)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-10-18
      • 2019-06-16
      • 2014-11-13
      • 1970-01-01
      • 2020-12-07
      • 1970-01-01
      • 2021-01-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多