代码之家  ›  专栏  ›  技术社区  ›  iDeveloper

如何在iOS中设置文本字段的数字范围?

  •  -2
  • iDeveloper  · 技术社区  · 9 年前

    我想设定一个范围,即35万美元&$文本字段为800000。如果输入的数字小于此范围,则应弹出警告消息。请帮助

    3 回复  |  直到 8 年前
        1
  •  0
  •   Anoop Vaidya    9 年前

    在Objective-C中,使用 NSNumberFormatter 您可以这样使用:

    NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
    
    nf.minimum = @10;
    nf.maximum = @20;
    
    NSNumber *a = [nf numberFromString:@"12"];
    NSNumber *b = [nf numberFromString:@"22"]; 
    //if the number is beyond the range, it will return nil, so in above b is nil
    //so the following check will show the log and alert
    
    if (!a || !b) {
        NSLog(@"Either of them is out of range");
        //show the UIAlert here
    }
    

    编辑:

    在以下情况下,您应该调用上面的函数:

    1. 用户输入一个值并执行一些操作。在动作开始时,使用上面的。

    2. 或者每次用户进入并离开文本字段时,请在 textFieldDidEndEditing: 委托方法 UITextField .

    笔记 :因为您的号码已经 $ 前缀,请确保将货币样式设置为 nf 而不是修剪它。

        2
  •  -1
  •   rptwsthi    9 年前

    使用 - (void) textViewDidEndEditing:(UITextView *)textView 方法检查 intergerValue 如果不符合您的要求,则显示弹出窗口。

    如果想随时查看,请使用 - (BOOL) textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

    NSString *finalText = [textView.text stringByAppendingPathComponent:text];
    finalText = [finalText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    //enable button
    if ([finalText integerValue] < 350000 || [finalText integerValue] > 850000) //do what you wanna do
    

    确保$不在文本字段中,或者在使用之前将其删除 integerValue .

        3
  •  -1
  •   Piyush    9 年前

    这可能很有用

    -(void)viewDidLoad
        {        
          [txt addTarget:self action:@selector(CheckingMethod:) forControlEvents:UIControlEventValueChanged];
        }
    
    -(IBAction)CheckingMethod:(id)sender
       {
    
       if(txt.text.length>9) {
         //your popupview
       }
        else{
         }
       }