简体   繁体   English

迅速在textview中允许退格2

[英]allowing backspace in textview in swift 2

I want to restrict my textview to 50 characters. 我想将textview限制为50个字符。 I did it, but I am unable to press backspace after 50 characters. 我做到了,但是我不能在50个字符后按退格键。 How to solve the problem ? 如何解决问题? My code is as below (Note: 'txtv' is my textview name) 我的代码如下(注意:“ txtv”是我的textview名称)

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

        if (self.txtv.text.characters.count) >= 50 {
         return false
        }
        return true
    }

if users cutting text, or deleting strings longer than a single character (ie if they select and then hit backspace), do like this 如果用户剪切文本或删除比单个字符长的字符串(即,如果他们选择然后按下退格键),请执行以下操作

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
return textView.text.characters.count + (text.characters.count - range.length) <= 50
}

You haven't check incoming text, you should do that before before limiting text input. 您尚未检查传入的文本,应在限制文本输入之前进行检查。

if text.characters.count == 0 { // if backspace
    return true
}

if (self.txtv.text.characters.count) >= 50 {
     return false
    }
    return true
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM