我將此Objective-C項目(TSCurrencyTextField)轉換爲Swift。它是格式化爲接受貨幣值的UITextField
子類。 This是我試圖轉換的.m
文件。覆蓋UITextField委託方法
其中,UITextField
的方法shouldChangeCharactersInRange
被TSCurrencyTextField
類型的參數覆蓋。像這樣(看最後一種方法),
@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
這是我的Swift轉換。
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
}
}
但我得到以下錯誤。
Objective-C的方法 '文本字段:shouldChangeCharactersInRange:replacementString:' 衝突帶有可選要求方法 「文本字段(:shouldChangeCharactersInRange:replacementString通過方法 '::shouldChangeCharactersInRange replacementString :)文本字段(' 提供 :)'in protocol'UITextFieldDelegate'
如何解決這個錯誤?