ios – SwiftUI TextField forestall sure characters from being entered?


How can I forestall sure characters from being entered into my SwiftUI TextField in order that when a un-allowed character is entered it’s fully ignored or changed with “”.

My code beneath solely works by specifying a single character to disregard however I would like to have the ability to specify many allowed characters with out utilizing a regex in my case (for readability).

I used to be making an attempt to make it work based mostly on current SO articles however want help with methods to verify each new character as it’s entered by evaluating it to a variety of allowed characters.

The TextField would additionally want to stop areas from being entered…

I’ve learn plenty of SO articles on this NOT FOR SWIFTUI TEXTFIELDS AND they aren’t simply understood with regex expressions.

enum InputType {
    case username
    case code
}

struct AccountInput: View {
    let placeholder: String
    @Binding var enter: String
    
    let inputType: InputType
 
    var physique: some View {
        HStack {
            TextField(placeholder, textual content: $enter)
                .onChange(of: enter) { _ in
                    swap inputType {
                    case .username:
                        let allowedCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-"
                        let allowedCharacterSet = CharacterSet(charactersIn: allowedCharacters)
                        let typedCharacterSet = CharacterSet(charactersIn: enter)
                        enter = enter.replacingOccurrences(of: ???, with: "")
                        // ^ HOW CAN I MODIFY THIS TO CHECK AND SEE IF CHARACTER IS CONTAINED IN ALLOWED CHARACTER SET AND IGNORE SPACES???
                    case .code:
                        let allowedCharacters = "0123456789"
                        let allowedCharacterSet = CharacterSet(charactersIn: allowedCharacters)
                        let typedCharacterSet = CharacterSet(charactersIn: enter)
                        enter = enter.replacingOccurrences(of: " ", with: "")
                    }
                }
        }
    }

    init(placeholder: String, enter: Binding<String>, inputType: InputType) {
        self.placeholder = placeholder
        self._input = Binding(projectedValue: enter)
        self.inputType = inputType
    }
    
}

Similar Posts

Leave a Reply

Your email address will not be published.