在TextView

时间:2015-12-15 14:57:25

标签: ios swift uitextview

我只是想在XCode 7.1.1中使用以下函数在TextView中隐藏键盘,但它不起作用。

我该如何解决这个问题?

class pictureViewController: UIViewController, UITextViewDelegate {

    @IBOutlet weak var dedicatoriaCentradaTextView: UITextView!

    override func viewDidLoad() {
        dedicatoriaCentradaTextView.delegate = self
    }

    func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {

        if(text == "\n") {
            dedicatoriaCentradaTextView.resignFirstResponder()
            return false
        }
        return true
    }
}

2 个答案:

答案 0 :(得分:3)

当重载viewDidLoad()方法来设置文本视图的委托时,可能应该保留super.viewDidLoad():

override func viewDidLoad() {
    super.viewDidLoad()

    // Handle the user input in the text view through delegate callbacks
    dedicatoriaCentradaTextView.delegate = self
}

此后,在您几乎尝试正确的情况下,请使用textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String)协议中的UITextViewDelegate方法:

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

但请注意,您在上述方法中使用本地UITextView实例(方法作用域中的本地)。

使用上述建议,您的pictureViewController课程应该是

class pictureViewController: UIViewController, UITextViewDelegate {

    @IBOutlet weak var dedicatoriaCentradaTextView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Handle the user input in the text view through delegate callbacks
        dedicatoriaCentradaTextView.delegate = self
    }

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

最后请注意,通过Swift编码约定,您的类名应以大写字母开头。即,将您的班级pictureViewController重命名为PictureViewController

答案 1 :(得分:0)

只需在您的观看中致电endEditing