我将此Objective-C项目(TSCurrencyTextField)转换为Swift。它是一个UITextField
子类,其格式设置为接受货币值。 This是我尝试转换的.m
文件。
其中,使用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 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
}
}
但我收到以下错误。
Objective-C方法 &#39;文本字段:shouldChangeCharactersInRange:replacementString:&#39;提供 通过方法 &#39;文本框(:shouldChangeCharactersInRange:replacementString:)&#39; 与可选的需求方法冲突 &#39;文本框(:shouldChangeCharactersInRange:replacementString:)&#39;在 protocol&#39; UITextFieldDelegate&#39;
如何解决此错误?
答案 0 :(得分:1)
对于您要完成的任务,您不需要继承UITextFieldDelegate。
而是在init方法中,使用适当的函数将目标添加到self。
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
}
答案 1 :(得分:0)
对于类型和编译检查,Obj-c更加自由和简单,其中Swift不是。在swift中,您应该在声明时实现委托函数,而不是尝试更改任何类型。然后,您可以在实现中验证类型(使用if let
)。