当我从键盘输入每个字符时,我试图添加空格,但问题是我无法删除,复制或编辑文本。
- (BOOL) textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string
{
NSUInteger length = [textField.text length] + [string length] - range.length;
if ([textField tag] == textTag && newLength <= 10) {
textField.text = [textField.text stringByAppendingString:@" "];
length ++;
NSLog(@"%d", length);
} else {
NSLog(@"%d", length);
return NO;
}
return YES;
}
答案 0 :(得分:1)
你也可以这样做..
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSUInteger length = [textField.text length] + [string length] - range.length;
if (length < 10) {
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSString *lastString = [NSString stringWithFormat:@"%c",[newString characterAtIndex:newString.length-1]];
if(![lastString isEqualToString:@" "] && ![string isEqualToString:@""])
newString = [newString stringByAppendingString:@" "];
else {
NSRange tempR = NSMakeRange(range.location-1, 2);
newString = [textField.text stringByReplacingCharactersInRange:tempR withString:@""];
}
textField.text = newString;
}
return NO;
}
答案 1 :(得分:0)
试试这个:
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSUInteger length = [textField.text length] + [string length] - range.length;
if (length < 10) {
textField.text = [textField.text stringByAppendingString:@" "];
length++;
NSLog(@"%d", length);
}
else if (length >= 10 && string.length > 0)
{
NSLog(@"%d", length);
return NO;
}
if (string.length == 0) {
textField.text = [textField.text substringWithRange:NSMakeRange(0, length - 1)];
return YES;
}
return YES;
}