【问题标题】:How to set a range of numbers for textfield in iOS?如何在 iOS 中为文本字段设置数字范围?
【发布时间】:2016-01-08 11:36:32
【问题描述】:

我想为文本字段设置一个范围,即介于 $350000 和 $800000 之间。如果输入的数字小于此范围,则应弹出警告消息。请帮忙

【问题讨论】:

  • 请提供例如@AnoopVaidya
  • 每当焦点从文本字段移开时,将其文本解析为 int 并检查它是否在所需范围内

标签: ios objective-c iphone xcode cocoa-touch


【解决方案1】:

在 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. 或者每次用户进入和离开文本域,然后在UITextFieldtextFieldDidEndEditing:委托方法中调用上述。

注意:由于您的号码以$为前缀,请确保您在nf中也设置了货币样式,而不是修剪它。 p>

【讨论】:

  • 我怀疑 OP 知道何时在他的情况下运行该代码,您介意包含一些有关何时调用您的代码的信息吗?
  • @luk2302:更新了,希望他现在可以实现。
  • 像专业人士一样工作 :) 谢谢@AnoopVaidya
  • @Ashu:在答案中又添加了一条注释。
  • 是的,它以前不起作用,然后我从中删除了 $。现在可以使用了。
【解决方案2】:

使用- (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 之前将其删除。

【讨论】:

  • 我不想变长...@rptwsthi
【解决方案3】:

这很有帮助

-(void)viewDidLoad
    {        
      [txt addTarget:self action:@selector(CheckingMethod:) forControlEvents:UIControlEventValueChanged];
    }

-(IBAction)CheckingMethod:(id)sender
   {

   if(txt.text.length>9) {
     //your popupview
   }
    else{
     }
   }

【讨论】:

  • 这有什么帮助?请至少包含一点解释 - 现在它在任何地方都没有 OP。
  • 设置你的文本字段发送的事件值更改(你也可以在你的故事板中设置)而不是你可以把你的验证放在方法中
  • 为什么他每次输入文本字段时都要加载视图?
猜你喜欢
  • 1970-01-01
  • 2012-07-25
  • 1970-01-01
  • 1970-01-01
  • 2015-07-25
  • 2014-10-06
  • 2021-08-31
  • 2023-02-23
  • 2013-10-13
相关资源
最近更新 更多