xcode 使用 Swift 格式化文本字段中的数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24193408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 05:04:49  来源:igfitidea点击:

Format Numbers in Textfields using Swift

xcodeuitextfieldswiftios8

提问by user3724253

I am trying to format a number from a UITextfield, as its being typed, to a decimal with commas.

我正在尝试将数字从 a 格式化为UITextfield带逗号的小数。

I have done so with the following code:

我使用以下代码完成了此操作:

@IBAction func editingDidBegin(sender : AnyObject)
{
    costField.addTarget(self, action: Selector("textFieldDidChange:"), forControlEvents: UIControlEvents.EditingChanged)
}

func textFieldDidChange(theTextField:UITextField) -> Void
{
    var textFieldText = theTextField.text.stringByReplacingOccurrencesOfString(",", withString: " ", options: NSStringCompareOptions.RegularExpressionSearch, range: Range(start: theTextField.text.startIndex, end: theTextField.text.endIndex))
    var formatter:NSNumberFormatter = NSNumberFormatter()
    formatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
    var formattedOutput = formatter.stringFromNumber(textFieldText.bridgeToObjectiveC().integerValue)

    costField.text = formattedOutput
}

The problem with this, is after four digits are entered, everything after the comma is deleted. For example if I enter 4000 it formats to 4,000, then if I type another number like 8 it reformats to 48.

问题是,输入四位数字后,逗号后的所有内容都被删除。例如,如果我输入 4000,它会格式化为 4,000,然后如果我输入另一个数字,例如 8,它会重新格式化为 48。

Is there another way I can format this, maybe through IB or how can I fix the code?

有没有另一种方法可以格式化它,也许是通过 IB 或者我如何修复代码?

回答by Jean Le Moignan

Replace the line with:

将该行替换为:

var textFieldText = theTextField.text.stringByReplacingOccurrencesOfString(",", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range: Range(start: theTextField.text.startIndex, end: theTextField.text.endIndex))

(I only removed the space between the double quotes).

(我只删除了双引号之间的空格)。

Fact is, NSNumberFormatter doesn't like the added spaces in the string.

事实是, NSNumberFormatter 不喜欢字符串中添加的空格。

Works fine afterwards.

之后工作正常。

回答by Christopher Wade Cantley

I know I am late to the party but this worked well for me.

我知道我参加聚会迟到了,但这对我很有效。

var phoneNumber = " 1 (888) 555-5551    "

var strippedPhoneNumber = "".join(phoneNumber.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet))

It takes out the spaces and strips out the non decimal numeric characters.

它去掉空格并去掉非十进制数字字符。

The end result is "1888555551"

最终结果是“1888555551”

回答by fonz

I've updated this answer to the newest version of swift. This borrows 90% from the two answers above however, also accounts for nil exception from the textfield when the textfield is cleared.

我已将此答案更新为最新版本的 swift。这从上面的两个答案中借用了 90%,但是,当文本字段被清除时,文本字段的异常也为零。

func textFieldDidChangeCommas(theTextField:UITextField) -> Void
{
    if theTextField.text != nil {

        var textFieldText = theTextField.text!.stringByReplacingOccurrencesOfString(",", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range: Range(start: theTextField.text!.startIndex, end: theTextField.text!.endIndex))
        var formatter:NSNumberFormatter = NSNumberFormatter()
        formatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
        if textFieldText != "" {
            var formattedOutput = formatter.stringFromNumber(Int(textFieldText)!)
            costField.text = formattedOutput
        }
    }
}