Search code examples
iosswiftuitextfielduitextviewswift-extensions

Single extension for UITextView and UITextField in Swift


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.


Solution

  • Maybe this will work, since UIView is the parent class of them, downside is probably this will appear on all kinds of view, not sure if there's any other way to achieve what you need:

    extension UIView  {
        func addDoneButtonOnKeyboardWith(selector : Selector)
        {
            if self is UITextField || self is UITextView {
                //do something
            }
        }
    }