用于textfield的Swift两个代表函数
问题描述:
我在viewController中有两个文本区域。一个是“金额”,一个是“利率”。对于“金额”,我使用委托功能来控制他们输入的时间,它会自动添加逗号和$。这里是代码:用于textfield的Swift两个代表函数
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
}
对于“利率”,我想使输入自动添加%和限制只有一个小数点。我如何才能实现它我已经有一个委托功能。
答
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
}