Is there a way to override a view modifier?

1.4k views Asked by At

I have a custom TextField and want to be able to use the .keyboardType(.numberPad) modifier on the CustomTextInputField rather than having to send it through an initializer. Is this possible to override the modifier or maybe get access to the keyboard type through the environment, is there any other suggestion?

struct CustomTextInputField: View {

    @Binding private var text: String

    init(text: Binding<String>) {
        self._text = text
    }

    var body: some View {
        TextField("Type Text Here", text: $text)
    }
}

1

There are 1 answers

0
Asperi On

Yes, we can implement own variant of generic modifier for our custom view. Here is possible solution:

struct CustomTextInputField: View {
    
    @Binding private var text: String
    
    private var keyboard = UIKeyboardType.default
    
    init(text: Binding<String>) {
        self._text = text
    }
    
    var body: some View {
        TextField("Type Text Here", text: $text)
            .keyboardType(keyboard)
    }
    
    func keyboardType(_ type: UIKeyboardType) -> some View {
        var result = self
        result.keyboard = type
        return result
    }
}