Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 want it on my app. No extra work needed.

How to implement this in Swift?

Many links only talks about add new keyboard in setting. I don't want that.

I'm quite new to UI please give me detail explanation.

like image 586
Team Avatar asked Oct 31 '15 08:10

Team


1 Answers

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.

like image 143
icant Avatar answered Sep 29 '22 14:09

icant