如何限制UITextField只接受Swift中的数字? [英] How to restrict UITextField to take only numbers in Swift?

查看:90
本文介绍了如何限制UITextField只接受Swift中的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

推荐答案

这是我的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.

希望它有所帮助:)

PS:我认为你无论如何都照顾了代表。

PS: I assumed you looked after the delegate anyway.

更新:Swift 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
}

这篇关于如何限制UITextField只接受Swift中的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆