gpt4 book ai didi

objective-c - 如何限制文本输入和字符数?

转载 作者:搜寻专家 更新时间:2023-10-30 19:51:31 25 4
gpt4 key购买 nike

我有一个文本字段,我想将可以输入的文本限制为 160 个字符。此外,我需要一个计数器来获取当前的文本长度。

我使用 NSTimer 解决了这个问题:

[NSTimer scheduledTimerWithTimeInterval:0.5 target:self 
selector:@selector(countText)
userInfo:nil
repeats:YES];

我这样显示长度:

-(void)countText{
countLabel.text = [NSString stringWithFormat:@"%i",
_textEditor.text.length];
}

这不是最好的计数器解决方案,因为它取决于时间而不是 keyUp 事件。有没有办法捕获这样的事件并触发一个方法?

另一个问题是,是否可以阻止/限制文本输入,例如通过在文本字段上提供最大长度参数?

最佳答案

这是(或应该是)委托(delegate)方法的正确版本:

- (BOOL)textView:(UITextView *)aTextView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
// "Length of existing text" - "Length of replaced text" + "Length of replacement text"
NSInteger newTextLength = [aTextView.text length] - range.length + [text length];

if (newTextLength > 160) {
// don't allow change
return NO;
}
countLabel.text = [NSString stringWithFormat:@"%i", newTextLength];
return YES;
}

关于objective-c - 如何限制文本输入和字符数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5529143/

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