2016-12-21 70 views
0

我試圖做一個UITextField輸入永久顯示爲貨幣格式,即使用戶正在編輯。它應該工作,如:UITextField顯示格式爲貨幣不帶小數

$0 

用戶類型1

$1 

用戶類型2

$12 

用戶類型0

$120 

用戶類型0

$1,200 

用戶類型0

$12,000 

我設法得到使用NumberFormatter最終的格式一樣

textField.text = (numberFormatter.string(from: NSNumber(value: Int(textField.text!)!)))?.components(separatedBy: ".")[0] 

但是,一旦我格式化的文本框的文本,隨後的輸入會導致類似的錯誤:

$1,000 

用戶類型0

$1,0000 //number formatter cannot recognise this as a format of currency 

反正我能夠控制輸入,讓用戶只需要在號碼鍵,但該值顯示在適當的貨幣與符號加逗號格式 - 例如,$ 1,200,000。不管數字的數量如何 - 但邏輯上高達10就足夠了。

我現在的文本框shouldChangeCharactersInRange是這樣的:

textField.text = numberFormatter.number(from: textField.text!)?.description 

    if(range.length == 1){ //Backspace 
     if(textField.text?.characters.count == 1){ 
      textField.text = "$0" 
      return false 
     } 
     return true 
    } 
    if(string.trimmingCharacters(in: CharacterSet.decimalDigits.inverted) == ""){ 
     textField.text = (numberFormatter.string(from: NSNumber(value: Int(textField.text!)!)))?.components(separatedBy: ".")[0] 
     return false 
    } 
    if(string == ".") { 
     textField.text = (numberFormatter.string(from: NSNumber(value: Int(textField.text!)!)))?.components(separatedBy: ".")[0] 
     return false 
    } 

    textField.text = (numberFormatter.string(from: NSNumber(value: Int(textField.text!.append(string)!)!)))?.components(separatedBy: ".")[0] 
    return false 
+0

也將是感激,如果有人可以提供提示,以幫助我減少括號的數量,使代碼外觀,而無需添加太多的線條幹淨。 –

回答

1

試試下面的代碼

extension ViewController: UITextFieldDelegate { 

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

     let text: NSString = (textField.text ?? "") as NSString 
     let finalString = text.replacingCharacters(in: range, with: string) 

     // 'currency' is a String extension that doews all the number styling 
     amountTextField.text = finalString.currency 

     // returning 'false' so that textfield will not be updated here, instead from styling extension 
     return false 
    } 
} 

extension String { 
    var currency: String { 
     // removing all characters from string before formatting 
     let stringWithoutSymbol = self.replacingOccurrences(of: "$", with: "") 
     let stringWithoutComma = stringWithoutSymbol.replacingOccurrences(of: ",", with: "") 

     let styler = NumberFormatter() 
     styler.minimumFractionDigits = 0 
     styler.maximumFractionDigits = 0 
     styler.currencySymbol = "$" 
     styler.numberStyle = .currency 

     if let result = NumberFormatter().number(from: stringWithoutComma) { 
      return styler.string(from: result)! 
     } 

     return self 
    } 
} 
+0

這很聰明!我一直在想用數字格式化程序來保持我的字符串,我完全錯過了這種可能性 –

+0

不客氣 – Matt

0

可以使用的UITextField的leftView和rightView特性,如下圖所示:這將只需要在輸入的左側顯示「$」符號的護理領域。

override func viewDidLoad() { 
     super.viewDidLoad() 

     let label = UILabel(frame: CGRect(x :0,y :0,width :10,height: 10)) 
     label.text = "$" 

     self.moneyTextField.leftViewMode = .always 
     self.moneyTextField.leftView = label 

    } 
+0

其實,我沒有太多的貨幣符號問題,因爲數字格式化程序將幫助照顧它。這是逗號,「我」有麻煩。如果用戶在 –

2
// ViewController.swift 
// TextfieldDemo 
// 
// Created by piyush sinroja on 21/12/16. 


import UIKit 

class ViewController: UIViewController, UITextFieldDelegate { 

    @IBOutlet weak var txtDigit: UITextField! 

    var strDigit: String = String() 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 
     let label = UILabel(frame: CGRect(x :0,y :0,width :10,height: 10)) 
     label.text = "$" 
     self.txtDigit.leftViewMode = .always 
     self.txtDigit.leftView = label 

     txtDigit.layer.cornerRadius = 4.0 
     txtDigit.layer.masksToBounds = true 
     txtDigit.layer.borderColor = UIColor.lightGray.cgColor 
     txtDigit.layer.borderWidth = 1.0 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

    func textFieldDidBeginEditing(_ textField: UITextField) { 

    } 

    func textFieldDidEndEditing(_ textField: UITextField) { 

    } 

    func textFieldShouldReturn(_ textField: UITextField) -> Bool { 
     return true 
    } 

    func textField(_ textFieldToChange: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { 
     if textFieldToChange == txtDigit{ 
      let aSet = NSCharacterSet(charactersIn:"").inverted 
      let compSepByCharInSet = string.components(separatedBy: aSet) 
      let numberFiltered = compSepByCharInSet.joined(separator: "") 

      if numberFiltered == "" { 
       let new = txtDigit.text! 
       let fsf = new.substring(to: new.index(new.endIndex, offsetBy: -1)) 
       let currentString = fsf 
       let findStr = commaStrSet(currentString: currentString) 
       txtDigit.text = findStr 
       return false 
      } 
      else{ 
       let currentString = (textFieldToChange.text! as NSString) 
        .replacingCharacters(in: range, with: string) 
       let findStr = commaStrSet(currentString: currentString) 
       txtDigit.text = findStr 
      } 
     } 
     return false 
    } 

    func commaStrSet(currentString: String) -> String { 
     var replaceStr = currentString.replacingOccurrences(of: ",", with: "") 
     let length = replaceStr.characters.count 
     switch length { 
     case 4: 
      replaceStr.insert(",", at: replaceStr.index(replaceStr.startIndex, offsetBy: 1)) 
     case 5: 
      replaceStr.insert(",", at: replaceStr.index(replaceStr.startIndex, offsetBy: 2)) 
     case 6: 
      replaceStr.insert(",", at: replaceStr.index(replaceStr.startIndex, offsetBy: 1)) 
      replaceStr.insert(",", at: replaceStr.index(replaceStr.startIndex, offsetBy: 5)) 
     case 7: 
      replaceStr.insert(",", at: replaceStr.index(replaceStr.startIndex, offsetBy: 2)) 
      replaceStr.insert(",", at: replaceStr.index(replaceStr.startIndex, offsetBy: 5)) 
     case 8: 
      replaceStr.insert(",", at: replaceStr.index(replaceStr.startIndex, offsetBy: 1)) 
      replaceStr.insert(",", at: replaceStr.index(replaceStr.startIndex, offsetBy: 4)) 
      replaceStr.insert(",", at: replaceStr.index(replaceStr.startIndex, offsetBy: 7)) 
     case 9: 
      replaceStr.insert(",", at: replaceStr.index(replaceStr.startIndex, offsetBy: 2)) 
      replaceStr.insert(",", at: replaceStr.index(replaceStr.startIndex, offsetBy: 5)) 
      replaceStr.insert(",", at: replaceStr.index(replaceStr.startIndex, offsetBy: 8)) 
     case 10: 
      replaceStr.insert(",", at: replaceStr.index(replaceStr.startIndex, offsetBy: 1)) 
      replaceStr.insert(",", at: replaceStr.index(replaceStr.startIndex, offsetBy: 4)) 
      replaceStr.insert(",", at: replaceStr.index(replaceStr.startIndex, offsetBy: 7)) 
      replaceStr.insert(",", at: replaceStr.index(replaceStr.startIndex, offsetBy: 10)) 
     case 11,12,13,14,15: 
      replaceStr.insert(",", at: replaceStr.index(replaceStr.startIndex, offsetBy: 1)) 
      replaceStr.insert(",", at: replaceStr.index(replaceStr.startIndex, offsetBy: 4)) 
      replaceStr.insert(",", at: replaceStr.index(replaceStr.startIndex, offsetBy: 7)) 
      replaceStr.insert(",", at: replaceStr.index(replaceStr.startIndex, offsetBy: 10)) 
     default: 
      break 
     } 

     return replaceStr 
    } 
} 
+0

以上輸入的數字超過4個,則會打破格式設置以上代碼可以100%正常工作 –

+0

我嘗試了代碼,看起來偏移量是錯誤的,我試圖糾正它。感謝您的幫助。 –

+0

沒有它的工作正常。我只爲你做了,你可以使用你自己的邏輯 –