繁体   English   中英

如何向 UITextField & UITextView 添加方法?

[英]How to add a method to UITextField & UITextView?

我想把这样的东西放在UITextField & UITextView的方法中。

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM