Swift中UITextView和UITextField的单个扩展

时间:2016-11-22 09:35:44

标签: ios swift uitextfield uitextview swift-extensions

我想为UITextFieldUITextView创建一个扩展程序,并为其添加以下方法:

    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()
    }

我希望扩展方法仅适用于UITextFieldUITextView

3 个答案:

答案 0 :(得分:3)

也许这会有效,因为UIView是它们的父类,下行可能会出现在所有类型的视图中,不确定是否有其他方法可以实现所需:

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

答案 1 :(得分:3)

我有一个想法可以做你想要的,利用协议的默认实现。 技术上你仍然需要两个扩展,但它们都是完全空的。请考虑以下事项:

为您的方法创建协议,并提供默认实现:

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

然后使用此功能扩展UITextFieldUITextView

extension UITextField: DoneButtonBearer { }

extension UITextView: DoneButtonBearer { }

答案 2 :(得分:0)

您可以扩展的最近的类是UIControl,您可以扩展它,但是UIButtons和其他控件可以再次访问此方法。

因此,您可以使用静态方法扩展或子类化示例UIBarButtonItem。

class func addDoneBarButtonOnKeyboardFor(keyInput: UIControl <UIKeyInput>, usingSelector : 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
    keyInput.inputAccessoryView = keyBoardToolBar
    keyInput.reloadInputViews()
}

很抱歉,如果在Swift代码中犯了一些错误。现在开发Obj C.