Created
February 9, 2022 16:14
-
-
Save damodarnamala/3edec41fa4ae7d3db50e0d1580032ebd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| struct ContentView: View { | |
| let keyboard: UIKeyboardType = .emailAddress | |
| @State var text = "" | |
| var body: some View { | |
| Text("Hello, world!") | |
| .padding() | |
| TextField("Home", text: $text.limit(by: 10).trim(.numeric)) | |
| .keyboardType(keyboard) | |
| } | |
| } | |
| struct ContentView_Previews: PreviewProvider { | |
| static var previews: some View { | |
| ContentView() | |
| } | |
| } | |
| extension Binding where Value == String { | |
| func limit(by length: Int = 100) -> Binding<String> { | |
| if self.wrappedValue.count > length { | |
| DispatchQueue.main.async { | |
| self.wrappedValue = String(self.wrappedValue.dropLast()) | |
| } | |
| } | |
| return self | |
| } | |
| func trim(_ type: TrimType = .alphaNumeric) -> Binding<String> { | |
| DispatchQueue.main.async { | |
| self.wrappedValue = String(self.wrappedValue.trim(type: type)) | |
| } | |
| return self | |
| } | |
| } | |
| enum TrimType { | |
| case alphaNumeric | |
| case numeric | |
| } | |
| extension String { | |
| func trim(type : TrimType) -> String { | |
| switch type { | |
| case .alphaNumeric: | |
| let invalidChars = NSCharacterSet.alphanumerics.inverted | |
| return self.trimmingCharacters(in: invalidChars) | |
| case .numeric: | |
| let allowedCharacters = "1234567890" | |
| let allowedCharacterSet = CharacterSet(charactersIn: allowedCharacters).inverted | |
| return self.trimmingCharacters(in: allowedCharacterSet) | |
| } | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment