ios 将 UITextField 输入限制为 Swift 中的数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27215495/
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 03:51:26  来源:igfitidea点击:

Limit UITextField input to numbers in Swift

iosswiftuitextfield

提问by Santis

How can I get limit the user's TextField input to numbers in Swift?

如何在 Swift 中将用户的 TextField 输入限制为数字?

回答by Lyndsey Scott

You can use UITextFieldDelegate's shouldChangeCharactersInRangemethod to limit the user's input to numbers:

您可以使用UITextFieldDelegate'sshouldChangeCharactersInRange方法将用户的输入限制为数字:

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

    // Create an `NSCharacterSet` set which includes everything *but* the digits
    let inverseSet = NSCharacterSet(charactersInString:"0123456789").invertedSet

    // At every character in this "inverseSet" contained in the string,
    // split the string up into components which exclude the characters
    // in this inverse set
    let components = string.componentsSeparatedByCharactersInSet(inverseSet)

    // Rejoin these components
    let filtered = components.joinWithSeparator("")  // use join("", components) if you are using Swift 1.2

    // If the original string is equal to the filtered string, i.e. if no
    // inverse characters were present to be eliminated, the input is valid
    // and the statement returns true; else it returns false
    return string == filtered
}


Updated for Swift 3:

为 Swift 3 更新:

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

    // Create an `NSCharacterSet` set which includes everything *but* the digits
    let inverseSet = NSCharacterSet(charactersIn:"0123456789").inverted

    // At every character in this "inverseSet" contained in the string,
    // split the string up into components which exclude the characters
    // in this inverse set
    let components = string.components(separatedBy: inverseSet)

    // Rejoin these components
    let filtered = components.joined(separator: "")  // use join("", components) if you are using Swift 1.2

    // If the original string is equal to the filtered string, i.e. if no
    // inverse characters were present to be eliminated, the input is valid
    // and the statement returns true; else it returns false
    return string == filtered  
}

回答by Patrick Lin

For anyone looking for a shorter answer, I've found thisquite useful.

对于寻找更简短答案的人来说,我发现非常有用。

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    // remove non-numerics and compare with original string
    return string == string.filter("0123456789".contains)
}

Works in XCode 10.1, Swift 4.2

适用于 XCode 10.1、Swift 4.2

回答by Noman Haroon

Here is the simple solution which could help out.

这是可以提供帮助的简单解决方案。

Change Keyboard type to number

将键盘类型更改为数字

You can simply change keyboard type property of textfield to number pad here is the screen shot of the property to change

您可以简单地将文本字段的键盘类型属性更改为数字键盘,这里是要更改的属性的屏幕截图

Screen shot

截屏

回答by Akbar Khan

1st you have to inherit the UITextViewDelegate class with you own class

1st 你必须用你自己的类继承 UITextViewDelegate 类

class ViewController: UIViewController, UITextViewDelegate {

2nd add an IBOutlet

2 添加一个 IBOutlet

@IBOutlet weak var firstName: UITextField!

3rd you have to assure this object is using

第三,你必须确保这个对象正在使用

override func viewDidLoad() {
        super.viewDidLoad()
   firstName.delegate = self
}


func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField == firstName {
                let allowedCharacters = "1234567890"
                let allowedCharacterSet = CharacterSet(charactersIn: allowedCharacters)
                let typedCharacterSet = CharacterSet(charactersIn: string)
                let alphabet = allowedCharacterSet.isSuperset(of: typedCharacterSet)
                let Range = range.length + range.location > (fnameTF.text?.count)!

        if Range == false && alphabet == false {
            return false
        }


        let NewLength = (fnameTF.text?.count)! + string.count - range.length
        return NewLength <= 10


      } else {
        return false
    }
  }

回答by iOS

In swift 4.1 and Xcode 10

在 swift 4.1 和 Xcode 10 中

Add UITextFieldDelegateto your class

UITextFieldDelegate添加到您的班级

class YourViewController: UIViewController, UITextFieldDelegate

Then write this code in your viewDidLoad()

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

yourTF.delegate = self

Write this textfield delegate function

编写此文本字段委托函数

//MARK - UITextField Delegates
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    //For numers
    if textField == yourTF {
        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 ldindu

Well the iOS provides no such functionality where you can specify textfield to accept only numeric characters. The only way through would be, one of UITextFieldDelegatemethods, which is as follows,

好吧,iOS 没有提供这样的功能,您可以指定文本字段仅接受数字字符。唯一的方法是,UITextFieldDelegate方法之一,如下所示,

(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

You need to implement the following method and intercept the entered character and either through the following regular expression

您需要实现以下方法并拦截输入的字符,或者通过以下正则表达式

"^([0-9]+)?(\.([0-9]{1,2})?)?$"

or

或者

[NSCharacterSet decimalDigitCharacterSet]

you can find out whether the entered character is numeric and return YESif it matches the regular expression or character set else return NO.

您可以找出输入的字符是否为数字,如果匹配正则表达式或字符集则返回YES否则返回NO