我正在尝试在Swift中创建自定义UI文本字段。这是我的代码
public class AmountTextField : UITextField{
let currencyFormattor = NSNumberFormatter()
let amountTextFieldDelegate = AmountTextFieldDelegate()
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initTextField()
}
func initTextField(){
self.delegate = amountTextFieldDelegate
currencyFormattor.numberStyle = .CurrencyStyle
currencyFormattor.minimumFractionDigits = 2
currencyFormattor.maximumFractionDigits = 2
}
func setAmount (amount : Double){
let textFieldStringValue = currencyFormattor.stringFromNumber(amount)
self.text = textFieldStringValue
}
}
我的AmountTextFieldDelegate看起来像这样
class AmountTextFieldDelegate : NSObject, UITextFieldDelegate{
func textField(textField: AmountTextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let amount = getAmount() // calculates the amount
textField.setAmount(amount)
return false
}
}
我在shouldChangeCharactersInRange中将UITextField更改为AmountTextField,以便我可以在shouldChangeCharactersInRange中调用setAmount函数。但是当我这样做时,我得到了错误 -
Objective-C方法'textField:shouldChangeCharactersInRange:replacementString:'由方法提供'textField(:shouldChangeCharactersInRange:replacementString :)'与可选的需求方法'textField(:shouldChangeCharactersInRange:在协议'UITextFieldDelegate'
有没有办法可以在shouldChangeCharactersInRange中调用setAmount?
答案 0 :(得分:0)
考虑一下:
class AmountTextFieldDelegate : NSObject, UITextFieldDelegate {
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if let s = textField as? AmountTextField {
let amount = s.getAmount() // calculates the amount
s.setAmount(amount)
}
return true
}
}