2015-09-07 58 views
2

如何在uiTextField中輸入時使用固定小數分隔符(2位小數)。下面是示例圖像。我可以在UITextField中有一個固定的小數分隔符嗎?

下面的應用程序在輸入時保持格式,並在輸入數字時從左側移動數字。感謝所有幫助:)

fixed decimal separator

+0

什麼應該顯示看起來像每次按鍵後如果用戶輸入1 2 3 4 5 6? – vacawama

+0

@DharmeshKheni多數民衆贊成正是我正在尋找 –

+0

http://stackoverflow.com/a/29783546/2303865 –

回答

6

按這裏你需要的是完整的代碼:

import UIKit 

class ViewController: UIViewController { 

    @IBOutlet weak var inputField: UITextField! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     inputField.text = 0.twoDigits 
     inputField.addTarget(self, action: "editingNumberChanged", forControlEvents: UIControlEvents.EditingChanged) 
    } 
    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
    } 
    func editingNumberChanged() { 
     inputField.text = (Double(inputField.text!.numbersOnly.integerValue)/100).twoDigits 
    } 
} 

extension Double { 
    struct Number { 
     static let formatter = NSNumberFormatter() 
    } 
    var twoDigits: String { 
     Number.formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle 
     Number.formatter.minimumFractionDigits = 2 
     Number.formatter.maximumFractionDigits = 2 
     return Number.formatter.stringFromNumber(self)! 
    } 
} 

extension String { 
    var numbersOnly: String { 
     return "".join(componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet)) 
    } 
    var integerValue: Int { 
     return decimalNumber.integerValue 
    } 
    var decimalNumber: NSNumber { 
     return NSDecimalNumber(string: self) 
    } 
} 

結果:

enter image description here

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

+0

你是一個傳奇,謝謝 –

相關問題