我在viewController中有两个文本字段。一个是“金额”,一个是“利率”。对于“金额”,我使用委托函数来控制何时输入,它会自动添加逗号和$。这是代码:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let 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.usesSignificantDigits = false
formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
formatter.locale = NSLocale(localeIdentifier: "en_US")
let numberFromField = (NSString(string: digitText).doubleValue) / 100
newText = formatter.stringFromNumber(numberFromField)
if newText.isEqualToString("$0.00") {
newText = ""
}
// let attributedString = NSMutableAttributedString(string: newText as String)
// attributedString.addAttribute(NSKernAttributeName, value: CGFloat(0.05), range: NSRange(location: 0, length: newText.length))
//
// textField.attributedText = attributedString
textField.text = String(newText)
return false
}
对于“利率”,我想让输入自动添加%并限制为只有一个小数点。我怎么能意识到它已经有了一个委托功能。
答案 0 :(得分:0)
var amountTextField: UITextField?
var interestRateTextField: UITextField?
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if textField == amountTextField {
// Do you stuff with amountTextField
} else if textField == interestRateTextField {
// Do you stuff with interestRateTextField
}
return false
}