ios 如何限制 UITextField 在 Swift 中只取数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30973044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 06:32:29  来源:igfitidea点击:

How to restrict UITextField to take only numbers in Swift?

iosiphoneswiftipaduitextfield

提问by Hiren Panchal

I want the user to only enter numeric values in a UITextField. On iPhone we can show the numeric keyboard, but on iPad the user can switch to any keyboard.

我希望用户只在UITextField. 在 iPhone 上我们可以显示数字键盘,但在 iPad 上用户可以切换到任何键盘。

Is there any way to restrict user to enter only numeric values in a UITextField?

有什么办法可以限制用户在 a 中只输入数值UITextField

回答by Mr H

Here is my 2 Cents. (Tested on Swift 2 Only)

这是我的 2 美分。(仅在 Swift 2 上测试)

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

  let aSet = NSCharacterSet(charactersInString:"0123456789").invertedSet
  let compSepByCharInSet = string.componentsSeparatedByCharactersInSet(aSet)
  let numberFiltered = compSepByCharInSet.joinWithSeparator("")
  return string == numberFiltered

}

This is just a little bit more strict. No decimal point either.

这只是稍微严格一点。也没有小数点。

Hope it helps :)

希望能帮助到你 :)

PS: I assumed you looked after the delegate anyway.

PS:我假设你无论如何都会照顾代表。

Update: Swift 3.0:

更新:斯威夫特 3.0

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    let aSet = NSCharacterSet(charactersIn:"0123456789").inverted
    let compSepByCharInSet = string.components(separatedBy: aSet)
    let numberFiltered = compSepByCharInSet.joined(separator: "")
    return string == numberFiltered
}

回答by Hiren Panchal

Solution for swift 3.0 and above

swift 3.0及以上解决方案

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
  {
    let allowedCharacters = CharacterSet.decimalDigits
    let characterSet = CharacterSet(charactersIn: string)
    return allowedCharacters.isSuperset(of: characterSet)
  }

回答by iOS

In swift 4.1 and Xcode 9.4.1

在 swift 4.1 和 Xcode 9.4.1 中

Add UITextFieldDelegateto your class

UITextFieldDelegate添加到您的班级

class YourViewController: UIViewController, UITextFieldDelegate

Then write this code in your viewDidLoad()

然后在您的viewDidLoad() 中编写此代码

mobileNoTF.delegate = self

Write this textfield delegate function

编写此文本字段委托函数

//MARK - UITextField Delegates
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    //For mobile numer validation
    if textField == mobileNoTF {
        let allowedCharacters = CharacterSet(charactersIn:"+0123456789 ")//Here change this characters based on your requirement
        let characterSet = CharacterSet(charactersIn: string)
        return allowedCharacters.isSuperset(of: characterSet)
    }
    return true
}

回答by Cian

Swift 2.0

斯威夫特 2.0

For only allowing numbers and one "." decimal in uitextfield.

因为只允许数字和一个“.” uitextfield 中的十进制数。

func textField(textField: UITextField,shouldChangeCharactersInRange range: NSRange,replacementString string: String) -> Bool
{
    let newCharacters = NSCharacterSet(charactersInString: string)
    let boolIsNumber = NSCharacterSet.decimalDigitCharacterSet().isSupersetOfSet(newCharacters)
    if boolIsNumber == true {
        return true
    } else {
        if string == "." {
            let countdots = textField.text!.componentsSeparatedByString(".").count - 1
            if countdots == 0 {
                return true
            } else {
                if countdots > 0 && string == "." {
                    return false
                } else {
                    return true
                }
            }
        } else {
            return false
        }
    }
}

回答by Jamil Hasnine Tamim

IPhone only solution

仅限 iPhone 的解决方案

In whatever UITextField you're getting these values from, you can specify the kind of keyboard you want to appear when somebody touches inside the text field.

无论您从哪个 UITextField 获取这些值,您都可以指定当有人触摸文本字段时要显示的键盘类型。

E.G. a numeric-only keyboard.

EG 仅数字键盘。

Like this screenshot:

像这个截图:

enter image description here

在此处输入图片说明

Ipad

平板电脑

The iPad does not support the numeric keyboard, so your options are to either not support the iPad, validate the field post submit, or follow one of the other suggestions here to create same behaviors while running on an iPad.

iPad 不支持数字键盘,因此您的选择是不支持 iPad、验证现场提交提交,或按照此处的其他建议之一在 iPad 上运行时创建相同的行为。

回答by Raj Joshi

Accept decimal values in text fields with single (.)dot in Swift 3

在 Swift 3 中接受带有单个 (.) 点的文本字段中的十进制值

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let inverseSet = NSCharacterSet(charactersIn:"0123456789").inverted

    let components = string.components(separatedBy: inverseSet)

    let filtered = components.joined(separator: "")

    if filtered == string {
        return true
    } else {
        if string == "." {
            let countdots = textField.text!.components(separatedBy:".").count - 1
            if countdots == 0 {
                return true
            }else{
                if countdots > 0 && string == "." {
                    return false
                } else {
                    return true
                }
            }
        }else{
            return false
        }
    }
}

回答by ndmeiri

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    // return true if the replacementString only contains numeric characters
    let digits = NSCharacterSet.decimalDigitCharacterSet()
    for c in string {
        if !digits.characterIsMember(c) {
            return false
        }
    }

    return true
}

This solution will work even if the user switches keyboards or tries to paste a non-numeric string into the text field.

即使用户切换键盘或尝试将非数字字符串粘贴到文本字段中,此解决方案也将起作用。

Make sure to set the delegateproperty of the appropriate text field.

确保设置delegate相应文本字段的属性。

回答by SPatel

Use number formatter

使用数字格式化程序

Swift 4.x

斯威夫特 4.x

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
      let s = NSString(string: textField.text ?? "").replacingCharacters(in: range, with: string)
      guard !s.isEmpty else { return true }
      let numberFormatter = NumberFormatter()
      numberFormatter.numberStyle = .none
      return numberFormatter.number(from: s)?.intValue != nil
 }

回答by Aftab Ahmed

Extend your view controller like this:

像这样扩展你的视图控制器:

class MyViewController: UIViewController, UITextFieldDelegate

In the viewDidLoad function extend to your text field like this:

在 viewDidLoad 函数中,像这样扩展到您的文本字段:

myTextField.delegate = self

And then use the following function:

然后使用以下函数:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let isNumber = CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: string))
    let withDecimal = (
        string == NumberFormatter().decimalSeparator &&
        textField.text?.contains(string) == false
    )
    return isNumber || withDecimal
}

This will now make sure the user can enter only decimal digits.

这将确保用户只能输入十进制数字。

Swift 4 + Accepts Number only and accepts one separator

Swift 4 + 仅接受数字并接受一个分隔符

回答by shbli

Here is a simple solution, you need to connect the event "Editing changed" to this method in your controller

这是一个简单的解决方案,您需要将事件“编辑更改”连接到控制器中的此方法

Swift 4

斯威夫特 4

@IBAction func valueChanged(_ sender: UITextField) {
    if let last = sender.text?.last {
        let zero: Character = "0"
        let num: Int = Int(UnicodeScalar(String(last))!.value - UnicodeScalar(String(zero))!.value)
        if (num < 0 || num > 9) {
            //remove the last character as it is invalid
            sender.text?.removeLast()
        }
    }
}