xcode 如何限制文本输入和计数字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5529143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to limit text input and count characters?
提问by Upvote
I have a text field and I want to limit the text that can be entered to 160 chars. Besides I need a counter to get the current text length.
我有一个文本字段,我想将可以输入的文本限制为 160 个字符。此外我需要一个计数器来获取当前的文本长度。
I solved it using a NSTimer:
我使用NSTimer解决了它:
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self
selector:@selector(countText)
userInfo:nil
repeats:YES];
And I display the length this way:
我以这种方式显示长度:
-(void)countText{
countLabel.text = [NSString stringWithFormat:@"%i",
_textEditor.text.length];
}
This is not the best counter solution, because it depends on time and not on keyUp event. Is there a way to catch such an event and triggere a method?
这不是最好的计数器解决方案,因为它取决于时间而不是 keyUp 事件。有没有办法捕捉这样的事件并触发一个方法?
The othere thing is, is it possible to block/limit text input, e.g. by providing a max length parameter on the text field?
另一件事是,是否可以阻止/限制文本输入,例如通过在文本字段上提供最大长度参数?
回答by Matthias Bauch
This is (or should be) the correct version of the delegate method:
这是(或应该是)委托方法的正确版本:
- (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;
}
回答by nacho4d
implement some of UITextFieldDelegateprotocol methods
实现一些UITextFieldDelegate协议方法
_textEditor.delegate = self;
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
int len = [textField.text length];
if( len + string.length > max || ){ return NO;}
else{countLabel.text = [NSString stringWithFormat:@"%i", len];
return YES;} }
返回是;} }
回答by makboney
you can use the delegate method
你可以使用委托方法
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
if(textField.length < max){
return NO;
}else return YES;
}
}
and set the max length and return NO.
并设置最大长度并返回 NO。
回答by Himanshu Mahajan
Use following code to limit the characters in UITextField, following code accepts 25 characters in UITextField.
使用以下代码限制 UITextField 中的字符,以下代码接受 UITextField 中的 25 个字符。
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 25) ? NO : YES;
}