Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/106.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 输入时在Swift的文本字段中设置货币格式_Ios_Objective C_Swift - Fatal编程技术网

Ios 输入时在Swift的文本字段中设置货币格式

Ios 输入时在Swift的文本字段中设置货币格式,ios,objective-c,swift,Ios,Objective C,Swift,我试图在用户输入货币时,在Swift的文本字段中设置货币输入的格式 到目前为止,我只能在用户完成输入后才能成功格式化: @IBAction func editingEnded(sender: AnyObject) { let formatter = NSNumberFormatter() formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle formatter.locale = NSLocale(loc

我试图在用户输入货币时,在Swift的文本字段中设置货币输入的格式

到目前为止,我只能在用户完成输入后才能成功格式化:

@IBAction func editingEnded(sender: AnyObject) {

    let formatter = NSNumberFormatter()
    formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
    formatter.locale = NSLocale(localeIdentifier: "en_US")
    var numberFromField = NSString(string: textField.text).doubleValue

    textField.text = formatter.stringFromNumber(numberFromField)
}
但是,我希望在用户输入货币时对其进行格式化。当我尝试在文本字段操作“编辑已更改”或“值已更改”上执行此操作时,我只能输入1个数字(如果输入8,它将变为$8.00),但一旦输入第二个数字,所有内容都将变为$0.00,我无法再输入更多


有什么建议吗?我觉得这应该是一个简单的解决方案,但我不能完全解决它。

我从今天早些时候开始修改了该函数。非常适合“en_US”和“fr_fr”。然而,对于“ja_JP”,用100除以I do来创建小数是一个问题。您需要有一个switch或if/else语句,用于在格式化程序格式化时分隔带小数的货币和不带小数的货币。但我想这会让你进入你想要的空间

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var textField: UITextField!
    var currentString = ""

    override func viewDidLoad() {
        super.viewDidLoad()

        self.textField.delegate = self
    }

    //Textfield delegates
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { // return NO to not change text

        switch string {
        case "0","1","2","3","4","5","6","7","8","9":
            currentString += string
            println(currentString)
            formatCurrency(string: currentString)
        default:
            var array = Array(string)
            var currentStringArray = Array(currentString)
            if array.count == 0 && currentStringArray.count != 0 {
                currentStringArray.removeLast()
                currentString = ""
                for character in currentStringArray {
                    currentString += String(character)
                }
                formatCurrency(string: currentString)
            }
        }
        return false
    }

    func formatCurrency(#string: String) {
        println("format \(string)")
        let formatter = NSNumberFormatter()
        formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
        formatter.locale = NSLocale(localeIdentifier: "en_US")
        var numberFromField = (NSString(string: currentString).doubleValue)/100
        textField.text = formatter.stringFromNumber(numberFromField)
        println(textField.text )
    }
}

这适用于我使用NSNumberFormatter

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

    // Construct the text that will be in the field if this change is accepted
    var oldText = textField.text as NSString
    var newText = oldText.stringByReplacingCharactersInRange(range, withString: string) as NSString!
    var newTextString = String(newText)

    let digits = NSCharacterSet.decimalDigitCharacterSet()
    var digitText = ""
    for c in newTextString.unicodeScalars {
        if digits.longCharacterIsMember(c.value) {
            digitText.append(c)
        }
    }

    let formatter = NSNumberFormatter()
    formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
    formatter.locale = NSLocale(localeIdentifier: "en_US")
    var numberFromField = (NSString(string: digitText).doubleValue)/100
    newText = formatter.stringFromNumber(numberFromField)

    textField.text = newText

    return false
}

我制定了一个正常的货币格式(例如1是$1.00,88885是$88885.00,7555.8569是$7555.86)

@IBAction func lostpropertyclicked(sender: AnyObject) {
    var currentString = ""
    currentString = amountTF.text
    formatCurrency(string: currentString)
}

func formatCurrency(#string: String) {
    println("format \(string)")
    let formatter = NSNumberFormatter()
    formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
    formatter.locale = NSLocale(localeIdentifier: "en_US")
    var numberFromField = (NSString(string: currentString).doubleValue)
    currentString = formatter.stringFromNumber(numberFromField)!
    println(currentString )
}

基于@Robert answer。为Swift 2.0更新

//Textfield delegates
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { // return NO to not change text

    switch string {
    case "0","1","2","3","4","5","6","7","8","9":
        currentString += string
        formatCurrency(currentString)
    default:
        if string.characters.count == 0 && currentString.characters.count != 0 {
            currentString = String(currentString.characters.dropLast())
            formatCurrency(currentString)
        }
    }
    return false
}

func formatCurrency(string: String) {
    print("format \(string)")
    let formatter = NSNumberFormatter()
    formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
    formatter.locale = NSLocale(localeIdentifier: "en_US")
    let numberFromField = (NSString(string: currentString).doubleValue)/100
    self.amountField.text = formatter.stringFromNumber(numberFromField)
    print(self.amountField.text )
}
适用于Swift 3.0

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

        // Construct the text that will be in the field if this change is accepted

        switch string {
        case "0","1","2","3","4","5","6","7","8","9":
            currentString += string
            formatCurrency(currentString)
        default:
            if string.characters.count == 0 && currentString.characters.count != 0 {
                currentString = String(currentString.characters.dropLast())
                formatCurrency(currentString)
            }
        }
        return false    }

    func formatCurrency(_ string: String) {
        print("format \(string)")
        let formatter = NumberFormatter()
        formatter.numberStyle = .currency
        formatter.locale = findLocaleByCurrencyCode("NGN")
        let numberFromField = (NSString(string: currentString).doubleValue)/100
        let temp = formatter.string(from: NSNumber(value: numberFromField))
        self.amountTextField.text = String(describing: temp!.characters.dropFirst())
    }

func findLocaleByCurrencyCode(_ currencyCode: String) -> Locale? {

    let locales = Locale.availableIdentifiers 
    var locale: Locale?     
    for   localeId in locales {     
      locale = Locale(identifier: localeId)     
      if let code = (locale! as NSLocale).object(forKey: NSLocale.Key.currencyCode) as? String { 
        if code == currencyCode {
                return locale       
        }   
    } 
}    
return locale }
这对我很有用: 不过,变量的命名还需要改进。乘以10很容易,但计算出如何除以10并向下取整对于指针来说很棘手

    let numberFormatter = NumberFormatter()
    numberFormatter.numberStyle = .currency


    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField == amountTextField {
        guard let text = textField.text else {return true}

        let oldDigits = numberFormatter.number(from: text) ?? 0
        var digits = oldDigits.decimalValue

        if let digit = Decimal(string: string) {
            let newDigits: Decimal = digit / 100

            digits *= 10
            digits += newDigits
        }
        if range.length == 1 {
            digits /= 10
            var result = Decimal(integerLiteral: 0)
            NSDecimalRound(&result, &digits, 2, Decimal.RoundingMode.down)
            digits = result
        }

        textField.text = NumberFormatter.localizedString(from: digits as NSDecimalNumber, number: .currency)
        return false
    } else {
        return true
    }
}
斯威夫特5

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { // return NO to not change text

    switch string {
    case "0","1","2","3","4","5","6","7","8","9":
        currentString += string
        formatCurrency(string: currentString)
    default:
        if string.count == 0 && currentString.count != 0 {
            currentString = String(currentString.dropLast())
            formatCurrency(string: currentString)
        }
    }
    return false
}

func formatCurrency(string: String) {
    print("format \(string)")
    let formatter = NumberFormatter()
    formatter.numberStyle = NumberFormatter.Style.currency
    formatter.locale = NSLocale(localeIdentifier: "en_US") as Locale
    let numberFromField = (NSString(string: currentString).doubleValue)/100
    //replace billTextField with your text field name
    self.billTextField.text = formatter.string(from: NSNumber(value: numberFromField))
    print(self.billTextField.text ?? "" )
}

תודה㪡ך!太棒了,史蒂夫,你又救了我。简单问一个问题,你认为有没有办法允许用户输入一个数字,直到他们输入小数点之前它都是一个整数?比如说,输入8,输出将是“$8.00”,然后是9:$89.00,直到它们输入一个小数点,数字才保持完整?当用户按下后退按钮时会发生什么情况,我在按下后退按钮后尝试,文本将再次出现并从它的左侧开始,有没有想法使用Swift 2.0跟踪后退按钮事件这行代码:var array=array(string)var currentStringArray=array(currentString)需要类似于:var array=array(string.characters)var currentStringArray=array(currentString.characters)您可以使用../pow(10.0,Double(formatter.maximumFractionDigits))将其除以100工作正常。上面批准的解决方案对我来说有一个退格按钮问题。但是,这非常有效,不适用于在数字后面添加文本的货币。例如,瑞典、挪威、丹麦等将显示
10000,00瑞典克朗
,您无法删除任何内容。我不明白为什么这个答案会显示“RM”在美元金额前,只需将“en_MY”改为“en_US”