I have made a custom keyboard that gets loaded from an .xib file.
I decided to go with an in-app only keyboard rather than a system-wide keyboard because the documentation states:
Make sure a custom, systemwide keyboard is indeed what you want to develop. To provide a fully custom keyboard for just your app or to supplement the system keyboard with custom keys in just your app, the iOS SDK provides other, better options. Read about custom input views and input accessory views in Custom Views for Data Input in Text Programming Guide for iOS.
Implementation highlights
- Keyboard layout comes from Keyboard.xib, whose file owner is Keyboard.swift.
- Keyboard.xib uses auto layout to resize all individual keys (
UIButton
s) when the keyboard view size changes. - Use of a delegate to communicate between the keyboard view and the view controller.
- Use of the
inputView
method ofUITextField
to replace the system keyboard with my custom keyboard.
ViewController.swift
import UIKit
class ViewController: UIViewController, KeyboardDelegate {
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// initialize custom keyboard
let keyboardView = Keyboard(frame: CGRect(x: 0, y: 0, width: 0, height: 300))
keyboardView.delegate = self
// replace system keyboard with custom keyboard
textField.inputView = keyboardView
}
// required method for keyboard delegate protocol
func keyWasTapped(character: String) {
textField.insertText(character)
}
}
Keyboard.swift
import UIKit
protocol KeyboardDelegate {
func keyWasTapped(character: String)
}
class Keyboard: UIView {
var delegate: KeyboardDelegate?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initializeSubviews()
}
override init(frame: CGRect) {
super.init(frame: frame)
initializeSubviews()
}
func initializeSubviews() {
let view = NSBundle.mainBundle().loadNibNamed("Keyboard", owner: self, options: nil)[0] as! UIView
self.addSubview(view)
view.frame = self.bounds
}
@IBAction func keyTapped(sender: UIButton) {
self.delegate?.keyWasTapped(sender.titleLabel!.text!)
}
}
Concerns
- I never could find a single tutorial or full example of implementing an in-app only custom keyboard that makes use of the
inputView
method. This seems to work, but since I don't have anything else to compare it to, I wanted to run it by other programmers first. - I've gotten the impression from various reading that using .xib files to build a view is an outdated practice.