Richa Richa - 1 year ago 301
Objective-C Question

Using custom UITextField in UITextFieldDelegate functions

I am trying to create a custom UI Text field in Swift. Here is my code

public class AmountTextField : UITextField{

let currencyFormattor = NSNumberFormatter()

let amountTextFieldDelegate = AmountTextFieldDelegate()

required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)

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

And my AmountTextFieldDelegate looks like this

class AmountTextFieldDelegate : NSObject, UITextFieldDelegate{

func textField(textField: AmountTextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

let amount = getAmount() // calculates the amount

return false

I changed UITextField to AmountTextField in shouldChangeCharactersInRange so that I could call the setAmount function in shouldChangeCharactersInRange. But when I do that, I get the error -

Objective-C method 'textField:shouldChangeCharactersInRange:replacementString:' provided by method 'textField(:shouldChangeCharactersInRange:replacementString:)' conflicts with optional requirement method 'textField(:shouldChangeCharactersInRange:replacementString:)' in protocol 'UITextFieldDelegate'

Is there a way I can call the setAmount in shouldChangeCharactersInRange?

Answer Source

Consider this:

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
        return true
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download