SwiftUI:如何阻止文本字段中的某些字符? [英] SwiftUI: How to block certain characters in a textfield?

查看:21
本文介绍了SwiftUI:如何阻止文本字段中的某些字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用中有一个 url 地址栏,它只加载www.google.com"这种格式的 url;而不是https://www.google.com"

i have a url address bar in my app that only loads urls in this format "www.google.com" instead of "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://"每次.

I want the Textfield to block out these characters "https://" so that whenever a user copies and pastes a url from another browser, they don't have to manually delete "https://" every time.

推荐答案

你可以试试这样的:

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

这篇关于SwiftUI:如何阻止文本字段中的某些字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆