我已经为此工作了三天。我正在尝试格式化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
}
}
textField中的输出也是1234,但调试器中的输出是$ 1234.56
谢谢!
答案 0 :(得分:0)
在viewDidLoad
中尝试这一行,它能解决所有问题吗?
textField.delegate = self
答案 1 :(得分:0)
所以我明白了。然后,我下载了解决方案。但是,我不明白为什么会这样。为什么返回false(在转换textField之后)给出正确的解决方案?
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
newText = textField.text
let convertToANumber = string.toInt() //check the replacment string for a Int.
// 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)
textField.text = newText as String
return false//sends correctly formatted $123.45 to viewController
}
else {
return false}//returns false if checkToSeeIfItsANumber is nil