2016-06-07 121 views
0

我將此Objective-C項目(TSCurrencyTextField)轉換爲Swift。它是格式化爲接受貨幣值的UITextField子類。 This是我試圖轉換的.m文件。覆蓋UITextField委託方法

其中,UITextField的方法shouldChangeCharactersInRangeTSCurrencyTextField類型的參數覆蓋。像這樣(看最後一種方法),

@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'

如何解決這個錯誤?

回答

0

對於Swift不是的類型和編譯檢查來說,Obj-c更自由,更容易。在swift中,您應該在聲明時實現委託函數,而不是嘗試更改任何類型。然後,您可以在執行過程中驗證類型(使用if let)。

1

對於你要完成的任務,你不需要子類UITextFieldDelegate。

取而代之,在您的init方法中,使用適當的函數向自己添加一個目標。

override init(frame: CGRect) { 
    super.init(frame: frame) 
    self.addTarget(self, action: "formatText", for: .editingChanged) 
} 

required init?(coder aDecoder: NSCoder) { 
    super.init(coder: aDecoder) 
    self.addTarget(self, action: "formatText", for: .editingChanged) 
} 

func formatText() { 
    // Edit self.text here 
}