gpt4 book ai didi

ios - 限制uitextview中的字符数

转载 作者:IT王子 更新时间:2023-10-29 07:31:51 26 4
gpt4 key购买 nike

我正在给 TextView 发送一些字符串。

我正在应用以下方法将字符数限制为 140 个长度。

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
return [[textView text] length] <= 140;
}

除了退格键不起作用的第一个条件外,代码运行良好。 假设我已经达到了 140 个字符的限制,这样该方法就会给我 false 并且用户无法插入更多字符,但是在那之后当我尝试删除一些字符时, TextView 的行为就像它被禁用一样。

所以问题是:“如何从 textview.text 中删除字符或重新启用 TextView ?”

最佳答案

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
return textView.text.length + (text.length - range.length) <= 140;
}

这考虑到用户剪切文本,或删除比单个字符长的字符串(即,如果他们选择然后按退格键),或突出显示范围并粘贴比它短或长的字符串。

swift 4.0 版本

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

关于ios - 限制uitextview中的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2492247/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com