如何向UITextField和UITextView添加方法?

| 我想在
UITextField
UITextView
的方法中放入类似内容。
- (void)changeKeyboardType:(UIKeyboardType)keyboardType {
    paymentTextView.keyboardType = UIKeyboardTypeAlphabet;
    [paymentTextView resignFirstResponder];
    [paymentTextView becomeFirstResponder];
}
我该怎么做呢?我知道我可以同时为
UITextField
UITextView
创建类别,但是可以一次完成吗? 一枪,我的意思是用一种协议将其添加到两个类中,而不是将其分为两类,一类用于
UITextView
,一类用于
UITextField
。我听说协议类似于Ruby模块,但是在Ruby模块中,我可以实现该方法。在协议中,似乎只能声明方法但不能实现它。我还可以在协议中实现该方法,然后将此协议包含在“ 0”和“ 1”中吗? 如何在Cocoa中向现有协议添加方法?接近但不完全是。     
已邀请:
那这样的东西呢?
// UIView+UITextInputTraits.h

@interface UIView (UITextInputTraits)
- (void)changeKeyboardType:(UIKeyboardType)keyboardType;    
@end


// UIView+Additions.m

#import \"UIView+UITextInputTraits.h\"

@implementation UIView (UITextInputTraits)

- (void)changeKeyboardType:(UIKeyboardType)keyboardType {
    if ([self conformsToProtocol:@protocol(UITextInputTraits)]) {
        id<UITextInputTraits> textInput = (id<UITextInputTraits>)self;
        if (textInput.keyboardType != keyboardType) {
            [self resignFirstResponder];
            textInput.keyboardType = keyboardType;
            [self becomeFirstResponder];
        }
    }
}

@end
    
您可以为每个类别创建一个类别。 接口文件:
@interface UITextField (ChangeKeyboard)
- (void)changeKeyboardType:(UIKeyboardType)keyboardType;
@end
实施文件:
@implementation UITextField (ChangeKeyboard)
- (void)changeKeyboardType:(UIKeyboardType)keyboardType {
    self.keyboardType = keyboardType;
    [self resignFirstResponder];
    [self becomeFirstResponder];
}
@end
那就是添加这些的方法,但是我还没有测试功能。     
就像@Josh所说的那样,方法混乱不是您想要的。但是我真正想到的(我的缺点是在提交答案之前不进行更多研究)是在运行时在UITextView和UITextField上添加方法。尽管这需要更多代码来实现,但它可以为您提供所需的单次操作(您创建一个方法,并在运行时将其添加到UITextView和UITextField中) 这是关于它的博客文章: http://theocacao.com/document.page/327 http://www.mikeash.com/pyblog/friday-qa-2010-11-6-creating-classes-at-runtime-in-objective-c.html     

要回复问题请先登录注册