Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 272
PGDev Avatar asked Sep 19 '25 00:09

PGDev


1 Answers

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 { }

like image 135
Jacob King Avatar answered Sep 21 '25 18:09

Jacob King