故障设置的最大长度文本字段 [英] Trouble Setting A Maximum Length For A Text Field
问题描述
我无法设置的最大长度为文本字段的内容。我把过程实施我的头文件中UITextFieldDelegate。然后,我定义(然后叫)这个方法:
I'm having trouble setting a maximum length for the content of a text field. The process I took was implementing the UITextFieldDelegate in my header file. I then defined (and then called) this method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 5) ? NO : YES;
}
这是我用了这里的建议在网站上的方法。我也试过这样:
This was a method that I got by suggestion here on the site. I've also tried this:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSUInteger newLength = [zipCode.text length] + [string length] - range.length;
return (newLength > 5) ? NO : YES;
}
拉链code是的,我连接到文本字段的插座。每次我已经改变了code,我确信重新连接插座。我有一种感觉那就是我失去了一个非常简单的事情。道歉,如果这是一个有点令人费解,我有很多东西需要学习!谢谢你。
"zipCode" is the the outlet that I connected to the text field. Each time I've changed the code I've made sure to reconnect the outlet. I have a feeling it's a very simple thing that I'm missing. Apologies if this is a little convoluted, I have a lot to learn! Thanks.
推荐答案
试试这个:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
return (zipCode.text.length + string.length <= 5);
}
然后,在 viewDidLoad中
方法:
- (void)viewDidLoad {
zipCode.delegate = self;
//.....
[super viewDidLoad];
}
这篇关于故障设置的最大长度文本字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!