How to input currency format on a text field (from right to left) using Swift?

前端 未结 9 1020
甜味超标
甜味超标 2020-11-22 01:57

I have a number let’s say 0.00.

  • When the user taps 1. We should have 0.01
  • When the user taps 2. We should display 0.
9条回答
  •  爱一瞬间的悲伤
    2020-11-22 02:39

    Here is a code for swift 2

    @IBOutlet weak var txtAmount: UITextField!
    
    //MARK: - UITextField Delegate -
        func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool{
    
            if string.characters.count == 0 {
                return true
            }
    
            let userEnteredString = textField.text ?? ""
            var newString = (userEnteredString as NSString).stringByReplacingCharactersInRange(range, withString: string) as NSString
            newString = newString.stringByReplacingOccurrencesOfString(".", withString: "")
    
            let centAmount : NSInteger = newString.integerValue
            let amount = (Double(centAmount) / 100.0)
    
            if newString.length < 16 {
                let str = String(format: "%0.2f", arguments: [amount])
                txtAmount.text = str
            }
    
            return false //return false for exact out put
        }
    

    Note : Connect delegate for textField from storyboard or programatically

提交回复
热议问题