gpt4 book ai didi

iphone - 返回键的 Unichar 数字?

转载 作者:行者123 更新时间:2023-12-03 20:52:27 25 4
gpt4 key购买 nike

我有一个快速问题,但我在任何地方都找不到。我将文本字段限制为仅包含数字、小数和负号。但这样做时,我关闭了返回键。有人知道iOS返回键的unichar数字吗?我以为是十三,但这是行不通的。

 - (BOOL)textField:(UITextField *)textField 
shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSUInteger lengthOfString = string.length;
for (NSInteger loopIndex = 0; loopIndex < lengthOfString; loopIndex++)
{
unichar character = [string characterAtIndex:loopIndex];
if (character < 45) return NO; //45 - 57 we want
if (character > 57) return NO; // -./0123456789
if (character == 47) return NO; //47 we dont want, it is
// if (character == 36) return YES
}
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 5) ? NO : YES;
}

最佳答案

您可能还有其他原因要检查输入。 (我认为与 '\n' 相比是有效的),但这可能会更好:

-(BOOL)textFieldShouldReturn:(UITextField *)textField

编辑

处理浮点输入的更彻底的处理可能如下所示。关键思想是使用建议的替换构建候选字符串,然后测试整个字符串的语法有效性。通过这种方式,您可以处理用户在任意位置粘贴新文本而无需触摸代码。正则表达式只是一种紧凑/快速的指定语法的方法,您可以将自己的方法放入验证器中。

(我猜您可能希望将减号处理为不是字面上输入的一部分,而是需要负数的指示符。还假设长度限制是针对有效数字,而不仅仅是总字符数)

// answers true for a valid floating point literal, notwithstanding length
- (BOOL)isValidFloat:(NSString *)string {

// optional sign, followed by zero or more digits, followed by decimal, followed by zero or more digits
NSString *regex = @"([-+]?[0-9]*\\.?[0-9]*)";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
return [predicate evaluateWithObject:string];
}

#define kMAX_DIGITS 5

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

NSString *currentText = textField.text;
NSString *candidateText = [currentText stringByReplacingCharactersInRange:range withString:string];

// accept a minus sign at any time. Place it in front if it's not already there
if (string.length == 1 && [string characterAtIndex:0]=='-') {
if ([currentText rangeOfString:string].location == NSNotFound) {
textField.text = [string stringByAppendingString:currentText];
// since we just inserted the minus, answer no so it won't be inserted twice
return NO;
}
}

// the decimal and minus sign don't count against the length constraint
NSInteger decimalFudge = ([candidateText rangeOfString:@"."].location != NSNotFound)? 1 : 0;
NSInteger minusFudge = (candidateText.length > 0 && [candidateText characterAtIndex:0]=='-')? 1 : 0;
NSInteger maxLength = kMAX_DIGITS + decimalFudge + minusFudge;

return (candidateText.length <= maxLength) && [self isValidFloat:candidateText];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}

关于iphone - 返回键的 Unichar 数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10376566/

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