2

我有一个自定义TextField,希望能够在 上使用.keyboardType(.numberPad)修饰符,CustomTextInputField而不必通过初始化程序发送它。这是否可以覆盖修饰符或通过环境访问键盘类型,还有其他建议吗?

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

4

1 回答 1

3

是的,我们可以为我们的自定义视图实现自己的泛型修饰符变体。这是可能的解决方案:

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
    }
}
于 2020-12-12T04:53:50.073 回答