【发布时间】:2016-06-03 13:04:10
【问题描述】:
我正在尝试在 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:replacementString:) 冲突:)' 在协议'UITextFieldDelegate'中
有没有办法可以在 shouldChangeCharactersInRange 中调用 setAmount?
【问题讨论】:
-
设置金额有什么作用?您正在尝试覆盖委托中已存在的方法
-
不,只是格式化金额并将其添加到文本字段中。我添加了那段代码以使其更清晰
标签: objective-c swift uitextfield uitextfielddelegate