通过在textField Swift中点按来识别文本

时间:2019-05-14 06:22:37

标签: ios swift uitextview

我是新手,想为UITextView创建一个自定义类,在那里我可以通过在UITextView上点按它来获取文本。如何创建自定义UITextView类?

3 个答案:

答案 0 :(得分:1)

尝试一下,我创建了自定义textview类和协议,您需要在您的类中进行确认,并实现该方法以在每次单击textview时获取textview的文本。

class CustomTextView: UITextView {

    weak var delegateCustomTV: CustomTextViewDelegate?

    override func awakeFromNib() {
        super.awakeFromNib()
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.textViewTapped))
        self.addGestureRecognizer(tapGestureRecognizer)
    }

    @objc func textViewTapped() {
        delegateCustomTV?.preparedText(text: self.text ?? "")
    }
}

protocol CustomTextViewDelegate: class {
   func preparedText(text: String)
}

使用方式如我在下面使用的

class yourViewController: UIViewController, CustomTextViewDelegate {


    @IBOutlet weak var textView: CustomTextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        textView.delegateCustomTV = self
    }

    func preparedText(text: String) {
        // You will get your text here when you click on textview
        print(text)
    }
}

答案 1 :(得分:0)

尝试一下

 override func viewDidLoad() {
        super.viewDidLoad()

        self.textView.delegate = self 
    }
extension YourViewController: UITextViewDelegate
{

     //MARK:- TextView Editing begins Function     

    func textViewDidBeginEditing(_ textView: UITextView)
    {
        //TextView Editing Begin Function
    }



    // MARK:- TextView text replaced Function

    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool
    {
       //Character changed in textView
        return true
    }



     // MARK:- TextView End Editing function

    func textViewDidEndEditing(_ textView: UITextView)
    {        
       //End editing of textView
    }

}

答案 2 :(得分:0)

如果您想在每次点击文本视图时获取文本,则必须添加点击手势




      override func viewDidLoad() {
        super.viewDidLoad()

        self.textView.delegate = self

        let tap = UITapGestureRecognizer(target: self, action: #selector(self.textViewTapped(_:)))

        self.textView.addGestureRecognizer(tap)
}


 @objc func textViewTapped(_ sender: UITapGestureRecognizer){
       print(textView.text)
    }