gpt4 book ai didi

ios - 重写 UITextField 委托(delegate)方法

转载 作者:行者123 更新时间:2023-11-29 00:54:58 27 4
gpt4 key购买 nike

我正在将这个 Objective-C 项目 ( TSCurrencyTextField ) 转换为 Swift。它是一个 UITextField 子类,被格式化为接受货币值。 This是我要转换的 .m 文件。

其中,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 method 'textField:shouldChangeCharactersInRange:replacementString:' provided by method 'textField(:shouldChangeCharactersInRange:replacementString:)' conflicts with optional requirement method 'textField(:shouldChangeCharactersInRange:replacementString:)' in protocol 'UITextFieldDelegate'

如何修复此错误?

最佳答案

对于您要实现的目标,您不需要子类化 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
}

关于ios - 重写 UITextField 委托(delegate)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37682552/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com