如何将方法添加到UITextField& UITextView? [英] How to add a method to UITextField & UITextView?

查看:75
本文介绍了如何将方法添加到UITextField& UITextView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在UITextField& UITextView.

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

我该怎么做?我知道我可以同时为UITextField& UITextView,但可以一次完成吗?

How do I do this? I know I can create categories for both UITextField & UITextView but is it possible to do it in one shot?

一击,我的意思是使用一种协议将其添加到两个类中,而不是将其分为两类,一类用于UITextView& UITextField的一个.我听说协议类似于Ruby模块,但是在Ruby模块中,我可以实现该方法.在协议中,似乎只能声明方法但不能实现.我还可以在协议中实现该方法,然后将该协议包含在UITextField&中吗? UITextView?

By one shot, I mean add it to both classes with one protocol instead of making two categories, one for UITextView & one for UITextField. I've heard a protocol is similar to a Ruby module, but in a Ruby module, I can implement the method. In a protocol, it only seems that I can declare the method but not implement it. Can I also implement the method in the protocol, and then include this protocol in UITextField & UITextView?

如何将方法添加到可可中已有的协议?接近但不完全.

推荐答案

这样的事情怎么办?

// 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

这篇关于如何将方法添加到UITextField&amp; UITextView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆