美文网首页
IOS UITextField 金额输入框

IOS UITextField 金额输入框

作者: 阳光下的灰尘 | 来源:发表于2021-12-06 17:51 被阅读0次

/// 判断输入有效的金额开头

- (BOOL)isEnabelStartPriceWithReplaceText:(NSString *)replaceText
{
    /// 如果只输入. 则变成0.
    if ([self isEqualToString:@"."]) {
        return NO;
    }
    
    /// 如果输入0则变成0.
    if ([replaceText isEqualToString:@"0"] && [self isEqualToString:@"0"]) {
        return NO;
    }
    return YES;
}

///判断是否为有效金额输入

- (BOOL)isValidPriceInput {    
    if (self.length == 0) return YES;
    NSString *reg = @"^([1-9][0-9]{0,8}|[1-9][0-9]{0,8}\\.[0-9]{0,2}?|0|0\\.[0-9]{0,2}?)$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", reg];
    return [predicate evaluateWithObject:self];
}

使用示例

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString * str = [textField.text stringByReplacingCharactersInRange:range withString:string];
    /// 1.如果只输入. 则变成0.
    /// 2.如果只输入0则变成0.
    if (![str isEnabelStartPriceWithReplaceText:string]) {
        textField.text = @"0.";
        return NO;
    }
    
    //匹配有效金额
    if (!str.isValidPriceInput) {
        return NO;
    }
    return YES;
}

相关文章

网友评论

      本文标题:IOS UITextField 金额输入框

      本文链接:https://www.haomeiwen.com/subject/iuhnxrtx.html