在UITextFieldDelegate函数中使用自定义UITextField

时间:2016-06-03 13:04:11

标签: objective-c swift uitextfield uitextfielddelegate

我正在尝试在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'

中的replacementString :)'

有没有办法可以在shouldChangeCharactersInRange中调用setAmount?

1 个答案:

答案 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
    }
}