Swift中UITextView和UITextField的单个扩展 [英] Single extension for UITextView and UITextField in Swift

查看:201
本文介绍了Swift中UITextView和UITextField的单个扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为UITextFieldUITextView创建一个单独的扩展名,并向其中添加以下方法:

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

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

I want the extension method to be available only for UITextField and UITextView.

推荐答案

也许这是可行的,因为UIView是它们的父类,缺点是它可能会出现在各种视图上,不确定是否有实现您所需的其他方法:

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

这篇关于Swift中UITextView和UITextField的单个扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆