How to add a method to UITextField & UITextView?

后端 未结 3 747
深忆病人
深忆病人 2021-01-22 15:25

I want to put something like this in a method for UITextField & UITextView.

- (void)changeKeyboardType:(UIKeyboardType)keyboardType         


        
相关标签:
3条回答
  • 2021-01-22 16:00

    Like @Josh said, method swizzling isn't what you are looking for. However what I actually had in mind (My bad for not researching more into it before submitting an answer) is to add method at runtime on UITextView and UITextField. While this needs a bit more code to implement, it can give you the sort of one-shot you are looking for (You create a method and add it to both UITextView & UITextField at run-time)

    Here's a blog post about it:

    http://theocacao.com/document.page/327

    http://www.mikeash.com/pyblog/friday-qa-2010-11-6-creating-classes-at-runtime-in-objective-c.html

    0 讨论(0)
  • 2021-01-22 16:07

    What about something like this?

    // 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
    
    0 讨论(0)
  • 2021-01-22 16:25

    For each of these, you can create a category.

    Interface file:

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

    Implementation file:

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

    That would be the way to add these, but I haven't tested the functionality.

    0 讨论(0)
提交回复
热议问题