I\'m trying to add a custom UIToolBar to all of my keyboards with as little repetition. The way I\'m currently doing it requires me to add the code to all my viewDidLoads and as
You can make a UIToolbar subclass work by taking advantage of the responder chain. No need to change your view controllers. In Swift 3:
class KeyboardAccessoryToolbar: UIToolbar {
convenience init() {
self.init(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
self.barStyle = .default
self.isTranslucent = true
self.tintColor = UIColor(red: 76 / 255, green: 217 / 255, blue: 100 / 255, alpha: 1)
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(self.done))
let cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(self.cancel))
let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
self.items = [cancelButton, spaceButton, doneButton]
self.isUserInteractionEnabled = true
self.sizeToFit()
}
func done() {
// Tell the current first responder (the current text input) to resign.
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
func cancel() {
// Call "cancel" method on first object in the responder chain that implements it.
UIApplication.shared.sendAction(#selector(cancel), to: nil, from: nil, for: nil)
}
}
Then add the following to your applicationDidFinishLaunching
to apply this to all your keyboards:
let accessoryView = KeyboardAccessoryToolbar()
UITextField.appearance().inputAccessoryView = accessoryView
UITextView.appearance().inputAccessoryView = accessoryView