I want to create a single extension for both UITextField
and UITextView
and add a below method to it:
func addDoneButtonOnKeyboardWith(selector : Selector)
{
let keyBoardToolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 320, height: 30))
let barButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: selector)
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
keyBoardToolBar.items = [flexibleSpace, barButtonItem]
keyBoardToolBar.barStyle = .default
self.inputAccessoryView = keyBoardToolBar
self.reloadInputViews()
}
I want the extension method to be available only for UITextField
and UITextView
.
I have an idea that could do what you want, utilising the default implementation of a protocol. Technically you would still need two extensions but they would both be totally empty. Consider the following:
Create a protocol for your method, and provide a default implementation:
protocol DoneButtonBearer {
func addDoneButtonOnKeyboardWith(selector: Selector)
}
extension DoneButtonBearer {
func addDoneButtonOnKeyboardWith(selector: Selector) {
var view: UIView?
defer {
if view != nil {
let keyBoardToolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 320, height: 30))
let barButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: selector)
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
keyBoardToolBar.items = [flexibleSpace, barButtonItem]
keyBoardToolBar.barStyle = .default
view!.inputAccessoryView = keyBoardToolBar
view!.reloadInputViews()
}
}
if let textField = self as? UITextField {
view = textField
return
}
if let textView = self as? UITextView {
view = textView
return
}
}
}
Then just extend UITextField
and UITextView
with this functionality:
extension UITextField: DoneButtonBearer { }
extension UITextView: DoneButtonBearer { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With