我在.h文件中添加了委托UITextFieldDelegate
然后在 viewDidLoad 下的.m文件中:
[self textField:self.comment shouldChangeTextInRange:NSMakeRange(0,10) replacementText:@""];
然后添加了函数:
- (BOOL)textField:(UITextField *)textField shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if(textField.text.length >= 10)
{
return NO;
}
return YES;
}
我的目标是将键盘输入限制为10个字符的文本字段?我做错了什么或如何实现?
答案 0 :(得分:2)
这适用于退格和复制&糊
#define MAXLENGTH 10
- (BOOL)textField:(UITextField *) textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSUInteger oldLength = [textField.text length];
NSUInteger replacementLength = [string length];
NSUInteger rangeLength = range.length;
NSUInteger newLength = oldLength - rangeLength + replacementLength;
BOOL returnKey = [string rangeOfString: @"\n"].location != NSNotFound;
return newLength <= MAXLENGTH || returnKey;
}
答案 1 :(得分:1)
在[self textField:self.comment shouldChangeTextInRange:NSMakeRange(0,10) replacementText:@""];
中删除或评论此行viewDidLoad
。
在yourtextfield.delegate = self;
viewDidLoad
并实现以下委托方法,
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//allow back space
if (range.length == 0 && [string length] == 0) {
return YES;
}
if(textField.text.length >= 10)
{
return NO;
}
else{
return YES;
}
}
希望,这会有所帮助:)
答案 2 :(得分:1)
首先,你不应该明确地调用方法&#34; shouldChangeCharactersInRange :.当您在self.comment TextFiled中键入文本时,将调用此委托方法,前提是您已通过声明分配了委托,
self.comment.delegate = self.
您可以在xib或.m文件中指定委托。
您在shouldChangeCharactersInRange方法中添加的代码对于将输入屏蔽为10个字符是正确的。
希望这会有所帮助。谢谢。
答案 3 :(得分:0)
public func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if(range.length + range.location > textField.text?.characters.count)
{
return false
}
let newLength = (textField.text?.characters.count)! + string.characters.count - range.length;
return newLength <= self.maximumCharacterAllowed
}
答案 4 :(得分:0)
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if (textField == self.textField)
{
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 10) ? NO : YES;
}
return YES;
}
答案 5 :(得分:0)
使用此代码
#define KMAX_CHAR_LENGTH 20
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField.text.length >= KMAX_CHAR_LENGTH && range.length == 0) {
return NO; // do not change text
} else {
return YES; // Change Text
}
}
答案 6 :(得分:0)
使用此代码:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// Prevent crashing undo bug – see note below.
if(range.length + range.location > textField.text.length)
{
return NO;
}
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return newLength <= 25;
}