I'm converting this Objective-C project (TSCurrencyTextField) to Swift. It's a UITextField
subclass formatted to accept currency values. This is the .m
file I'm trying to convert.
In it, the UITextField
's method shouldChangeCharactersInRange
is overridden with a parameter of type TSCurrencyTextField
. Like so (look at the very last method),
@interface TSCurrencyTextFieldDelegate : NSObject <UITextFieldDelegate>
@property (weak, nonatomic) id<UITextFieldDelegate> delegate;
@end
@implementation TSCurrencyTextField
{
TSCurrencyTextFieldDelegate* _currencyTextFieldDelegate;
}
- (id) initWithFrame: (CGRect) frame
{
self = [super initWithFrame: frame];
if ( self )
{
[self TSCurrencyTextField_commonInit];
}
return self;
}
- (void) TSCurrencyTextField_commonInit
{
// ...
_currencyTextFieldDelegate = [TSCurrencyTextFieldDelegate new];
[super setDelegate: _currencyTextFieldDelegate];
}
- (void) setDelegate:(id<UITextFieldDelegate>)delegate
{
_currencyTextFieldDelegate.delegate = delegate;
}
- (id<UITextFieldDelegate>) delegate
{
return _currencyTextFieldDelegate.delegate;
}
@end
@implementation TSCurrencyTextFieldDelegate
- (BOOL) textField: (TSCurrencyTextField *) textField shouldChangeCharactersInRange: (NSRange) range replacementString: (NSString *) string
{
// ...
}
@end
Here's my Swift transalation.
protocol CurrencyTextFieldDelegate: NSObjectProtocol, UITextFieldDelegate {
weak var delegate: UITextFieldDelegate? { get set }
}
public class CurrencyTextField: UITextField {
override public var delegate: UITextFieldDelegate? {
get {
return self.delegate as? CurrencyTextFieldDelegate
}
set {
self.delegate = newValue
}
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
private func commonInit() {
}
}
// MARK: - CurrencyTextFieldDelegate
extension CurrencyTextField: CurrencyTextFieldDelegate {
public func textField(textField: CurrencyTextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
return false
}
}
But I get the following error.
Objective-C method 'textField:shouldChangeCharactersInRange:replacementString:' provided by method 'textField(:shouldChangeCharactersInRange:replacementString:)' conflicts with optional requirement method 'textField(:shouldChangeCharactersInRange:replacementString:)' in protocol 'UITextFieldDelegate'
How do I fix this error?