gpt4 book ai didi

swift - 使用新字符串格式化 UITextField 中的文本以实现右对齐和货币?

转载 作者:行者123 更新时间:2023-11-30 14:18:37 25 4
gpt4 key购买 nike

我已经为此工作了三天。我正在尝试将 UITextField 中的文本格式化为以货币格式输出并左对齐。我可以将变量中的文本格式化为货币输出,但不能在 textView 中格式化,并且 NSTextAlignment 不断给我一个错误。

import Foundation
import UIKit

class dollarFieldDelegate: NSObject, UITextFieldDelegate {
var currentString = ""
var newCurrency = ""
var newText: NSString = ""

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
newText = textField.text
textField.NSRightTextAlignment//Tried this several different ways, keep getting 'UITextField does not have member NSRightTextAlignment
let convertToANumber = string.toInt() //check the replacment string for a Int.
UIText
// If string does not contain an Int, stringByReplacingCharactersInRange is not executed
if convertToANumber != nil {

currentString += string
formatCurrency(string: currentString)
newText = newText.stringByReplacingCharactersInRange(range, withString: newCurrency)
println("in newText")
println(newText)
return true
}
else {
return false}//returns false if checkToSeeIfItsANumber is nil
}
func formatCurrency(#string: String) ->NSString{
//println("format \(string)")
let formatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
//formatter.locale = NSLocale(localeIdentifier: "en_US")
formatter.currencySymbol = "$"
var numberFromField = (NSString(string: currentString).doubleValue)/100
newText = formatter.stringFromNumber(numberFromField)!
//println(newCurrency)
return newCurrency
}

}

文本字段中的输出是 1234,但调试器中的输出是 $1234.56

谢谢!

最佳答案

在你的viewDidLoad中尝试这一行,它能解决任何问题吗?

textField.delegate = self

关于swift - 使用新字符串格式化 UITextField 中的文本以实现右对齐和货币?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30810715/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com