小编典典

用uiTextView关闭键盘

swift

我确信这并不是那么困难,但是我很难找到有关如何使用textview(而不是textfield)使用回车/完成键关闭键盘的信息。这是到目前为止我尝试过的(与文本字段一起使用。)

非常感谢您的帮助!

//  PostTravelQuestion.swift

class PostTravelQuestion: UIViewController, UITextViewDelegate {

    @IBAction func closepostpage(sender: AnyObject) {
        dismissViewControllerAnimated(true, completion: nil)
    }


    @IBOutlet var postquestion: UITextView!


    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        postquestion.delegate = self
    }

    self addDoneToolBarToKeyboard:self.textView


    /*func textViewShouldEndEditing(textView: UITextView) -> Bool {

        textView.resignFirstResponder()

        return true
    }*/

    /*override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        postquestion.resignFirstResponder()
        self.view.endEditing(true)
    }*/



    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    func textViewShouldReturn(textView: UITextView!) -> Bool {
        self.view.endEditing(true);
        return true;
    }
}

阅读 307

收藏
2020-07-07

共1个答案

小编典典

这对我有用:

import UIKit

class ViewController: UIViewController, UITextViewDelegate {


    @IBOutlet weak var textView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()

        textView.delegate = self
    }

    /* Updated for Swift 4 */
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if(text == "\n") {
            textView.resignFirstResponder()
            return false
        }
        return true
    }

    /* Older versions of Swift */
    func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
        if(text == "\n") {
            textView.resignFirstResponder()
            return false
        }
        return true
    }

}
2020-07-07