如何添加一个方法到UITextField和UITextView?

我想把这样的东西放在UITextFieldUITextView的方法中。

 - (void)changeKeyboardType:(UIKeyboardType)keyboardType { paymentTextView.keyboardType = UIKeyboardTypeAlphabet; [paymentTextView resignFirstResponder]; [paymentTextView becomeFirstResponder]; } 

我该怎么做呢? 我知道我可以为UITextFieldUITextView创build类别,但可以一次完成吗?

一次,我的意思是把它添加到两个类与一个协议,而不是两个类别,一个用于UITextView &一个用于UITextField 。 我听说一个协议类似于Ruby模块,但是在Ruby模块中,我可以实现这个方法。 在一个协议中,似乎我只能声明这个方法,却没有实现它。 我是否也可以在协议中实现该方法,然后将此协议包含在UITextFieldUITextView

如何在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 

对于每个这些,你可以创build一个类别。

接口文件:

 @interface UITextField (ChangeKeyboard) - (void)changeKeyboardType:(UIKeyboardType)keyboardType; @end 

实施文件:

 @implementation UITextField (ChangeKeyboard) - (void)changeKeyboardType:(UIKeyboardType)keyboardType { self.keyboardType = keyboardType; [self resignFirstResponder]; [self becomeFirstResponder]; } @end 

这将是添加这些的方式,但我没有testing的function。

就像@Josh所说的,方法混搭并不是你想要的。 然而,我实际上已经想到了(我提交一个答案之前不研究更多)是在UITextView和UITextField的运行时添加方法。 虽然这需要更多的代码来实现,但它可以给你一种你正在寻找的方法(你创build一个方法并将它添加到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