如何启用Only Numeric Digit Keyboard ios Swift

时间:2018-03-01 06:46:02

标签: ios swift xcode

我正在研究ios app当前面临的问题。我有三个文本字段,我希望用户在这些字段中输入数字输入,即1 2 3等。但在数字键盘中还有阿拉伯数字选项。有没有办法从键盘中删除阿拉伯数字选项?

4 个答案:

答案 0 :(得分:7)

使用此代码

textfield.keyboardType = .asciiCapableNumberPad

答案 1 :(得分:5)

您可以在委托方法中使用此功能。

 public static func convertStringtoArabic(_ paramString: String) -> String {
    var finalString: String = paramString
    finalString = finalString.replacingOccurrences(of: "٠", with: "0")
    finalString = finalString.replacingOccurrences(of: "١", with: "1")
    finalString = finalString.replacingOccurrences(of: "٢", with: "2")
    finalString = finalString.replacingOccurrences(of: "٣", with: "3")
    finalString = finalString.replacingOccurrences(of: "٤", with: "4")
    finalString = finalString.replacingOccurrences(of: "٥", with: "5")
    finalString = finalString.replacingOccurrences(of: "٦", with: "6")
    finalString = finalString.replacingOccurrences(of: "٧", with: "7")
    finalString = finalString.replacingOccurrences(of: "٨", with: "8")
    finalString = finalString.replacingOccurrences(of: "٩", with: "9")
    return finalString
}

您需要遵守的委托方法

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


    var newText = NSString(string: textField.text!).replacingCharacters(in: range, with: string)


    newText = Preferences.convertStringtoArabic(newText)

      // You can use this new text 

    let allowedCharacters = CharacterSet.decimalDigits
    let characterSet = CharacterSet(charactersIn: string)
    return allowedCharacters.isSuperset(of: characterSet)
}

答案 2 :(得分:2)

通过代码,您可以通过

完成
override func viewDidLoad() {
    super.viewDidLoad()
    yourTextField.keyboardType = .numberPad   //or .asciicapableNumberPad

}

如果您使用的是故事板,请按照

进行操作

将键盘类型更改为数字键盘。或ascii数字垫

enter image description here

答案 3 :(得分:2)

NSNumberFormatter格式化包含NSNumber个对象的单元格的文本表示形式,并将数值的文本表示形式转换为NSNumber个对象。  您可以更改数字格式&根据{{​​1}}的风格。

将任意数字转换为特定区域设置的功能。

Locale

致电功能

func numberToLocale(number : String, localeIdentifier: String) -> NSNumber?{
    let numberFormatter: NumberFormatter = NumberFormatter()
    numberFormatter.locale = Locale(identifier: localeIdentifier)
    guard let resultNumber = numberFormatter.number(from: number) else{
        return nil
    }
    return resultNumber
}

输出:86912881