【问题标题】:How to make 3 textFields in a ViewController take only integer input - XCode如何使 ViewController 中的 3 个文本字段仅接受整数输入 - XCode
【发布时间】:2015-07-23 16:36:42
【问题描述】:

我有 3 个名为 text1、text2 和 text3 的文本字段。

如何对它们进行编程以使其仅接受整数输入?

我见过的大多数类似问题都不适用于最新版本的 XCode(使用 Swift 2),并且不适合多个文本字段。

这个似乎很有帮助:How can I declare that a text field can only contain an integer?

【问题讨论】:

    标签: ios xcode


    【解决方案1】:

    首先按照iAnurag的建议将keyboardType更改为UIKeyboardTypeNumberPad

    并检查委托方法shouldChangeCharactersInRange 中的内容更改(使用 Swift 2.0 和 Xcode 7 测试的代码)

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    
        // Find out what the text field will be after adding the current edit
        let text = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
    
        if  text == "" {
            return true
        }
    
    
        if let _ = Int(text) {
            return true
        } else {
         return false
        }
    
    }
    

    【讨论】:

      【解决方案2】:

      这个集合非常简单直接的解决方案将UITextFieldkeyboardType属性设置为UIKeyboardTypeDecimalPad。这将不允许您的用户将字母放在UITextField

      斯威夫特

      self.promoTextField.keyboardType = UIKeyboardType.UIKeyboardTypeNumberPad
      

      目标 C

      myTextField.keyboardType = UIKeyboardTypeNumberPad;
      

      如果您使用故事板

      【讨论】:

      • 这行得通,@iAnurag!与 Aladin 的解决方案一起,它的功能就像一个魅力。
      【解决方案3】:

      按照@iAnurag 的建议进行操作,同时实现UITextFieldDelegate- textField:shouldChangeCharactersInRange:replacementString: 以检查replacementString 是否包含任何非数字字符。因为用户仍然可以将文本复制到其他地方并将其粘贴到文本字段中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-12-17
        • 2014-06-26
        • 1970-01-01
        • 2017-05-18
        • 1970-01-01
        • 2022-08-12
        • 2016-10-08
        相关资源
        最近更新 更多