Reputation: 413
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
})
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.
Upvotes: 0
Views: 359
Reputation: 36304
you could try something like this:
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)
}
}
Upvotes: 1