Richa Richa - 6 months ago 50
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)
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
}
}


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
textField.setAmount(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

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
            s.setAmount(amount)
        }
        return true
    }
}
Comments