how to use persian numbers in UItextField in swift

2019-03-06 14:43发布

问题:

Hi I am using text field in my swift3 application - I want when user enter a number in the text field instead of english number textfield shows persian numbers - my textfield keyboard has set to just enter number so the user can't use text inside the text field with keyboard so here is my codes that doesn't work

  override func viewDidLoad() {
         super.viewDidLoad()
 let numberFormatter = NumberFormatter()
    numberFormatter.locale = Locale(identifier: "fa")
    numberFormatter.numberStyle = NumberFormatter.Style.decimal
    let cm:Int? = Int(englishNumber.text!)

    if cm != nil {
    numberFormatter.string(from: NSNumber(value: cm!))
    myTextField.text = numberFormatter.string(from: NSNumber(value: cm!))!
    }

**remember that I used textfield Delegate and I want every Number that user entered change to Persian number and the user thought that writing Persian Numbers **

回答1:

try this :

 func convertEngNumToPersianNum(num: String)->String{
        let number = NSNumber(value: Int(num)!)
        let format = NumberFormatter()
        format.locale = Locale(identifier: "fa_IR")
        let faNumber = format.string(from: number)

        return faNumber!
    }