How to make custom keyboard only for my app in Swift?

前端 未结 1 1811
走了就别回头了
走了就别回头了 2021-01-06 00:18

How to make custom keyboard only for my app in Swift? I do not want people to go to setting and then add keyboard. I want them to be able to use it immediately when they wan

相关标签:
1条回答
  • 2021-01-06 01:17

    The UITextField and UITextView classes that you use for text input both have an inputView property. This property is nil by default, but if you provide it with a view, that view will pop up instead of the normal keyboard when editing that text field.

    To implement this, create a subclass of UIView that sets up your custom keyboard layout. Then, when you use a text field or text view in your app, you have to set it separately for every field, as follows:

    let myCustomKeyboard = MyCustomKeyboardView()
    myTextField.inputView = myCustomKeyboard
    

    That's it, now your text field uses the custom keyboard you provided.

    Since you want to use the keyboard globally in your app, and the keyboard has to be set separately for every text field or text view, this solution would lead to a lot of code duplication. Since code duplication is widely regarded as a bad thing to have, in your case a better implementation would be to subclass UITextField or UITextView (depending on which one you use, obviously), and set the keyboard in the constructor:

    class MyCustomKeyboardTextField: UITextField {
    
        override init() {
            super.init()
            setupCustomKeyboard()
        }
    
        required init(coder: aCoder) {
            super.init(aCoder)
        }
    
        override func awakeFromNib() {
            setupCustomKeyboard()
        }
    
        func setupCustomKeyboard() {
            // Set the custom keyboard
            self.inputView = MyCustomKeyboardView()
        }
    }
    

    Now the custom keyboard view will be used wherever you use this subclass.

    0 讨论(0)
提交回复
热议问题