iOS-键盘删除按钮的点击事件监听

iOS-键盘删除按钮的点击事件监听

刚刚做了一个功能,SMS登录,但是在UITextFeild中text为@""的时候,textFeild不响应(- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string)这个方法

在网上查了一下,最终灵感来了,找到最终方案,通过运行时来获取按钮,然后通过代理方法转出去,实现代理方法就可以了,费话不多说,上代码

#import <UIKit/UIKit.h>
@protocol SPTextFieldDelegate <UITextFieldDelegate>
@optional
- (void)textFieldDidDeleteBackward:(UITextField *)textField;
@end
@interface UITextField (SPExtension)
@property (weak, nonatomic) id<SPTextFieldDelegate> delegate;

@end
/**
 *  监听删除按钮
 *  object:UITextField
 */
extern NSString * const SPTextFieldDidDeleteBackwardNotification;

.m文件

#import <objc/runtime.h>
NSString * const SPTextFieldDidDeleteBackwardNotification = @"textfield_did_notification";

@implementation UITextField (SPExtension)

+ (void)load {
    Method method1 = class_getInstanceMethod([self class], NSSelectorFromString(@"deleteBackward"));
    Method method2 = class_getInstanceMethod([self class], @selector(sp_deleteBackward));
    method_exchangeImplementations(method1, method2);
}
- (void)sp_deleteBackward {
    [self sp_deleteBackward];
    
    if ([self.delegate respondsToSelector:@selector(textFieldDidDeleteBackward:)])
    {
        id <SPTextFieldDelegate> delegate  = (id<SPTextFieldDelegate>)self.delegate;
        [delegate textFieldDidDeleteBackward:self];
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:SPTextFieldDidDeleteBackwardNotification object:self];
}


调用

- (void)textFieldDidDeleteBackward:(UITextField *)textField {
    //删除事件
    if (textField == self.numberTextField2) {
        if ([textField.text isEqualToString:@""]) {
            [self.numberTextField1 becomeFirstResponder];
            [self textAll:NO];
            return;
    }
    }
    if (textField == self.numberTextField3) {
        if ([textField.text isEqualToString:@""]) {
            [self.numberTextField2 becomeFirstResponder];
            [self textAll:NO];
            return;
        }
    }
    if (textField == self.numberTextField4) {
        if ([textField.text isEqualToString:@""]) {
            [self.numberTextField3 becomeFirstResponder];
            [self textAll:NO];
            return;
        }
    }
    if (textField == self.numberTextField5) {
        if ([textField.text isEqualToString:@""]) {
            [self.numberTextField4 becomeFirstResponder];
            [self textAll:NO];
            return;
        }
    }
    if (textField == self.numberTextField6) {
         if ([textField.text isEqualToString:@""]) {
            [self.numberTextField5 becomeFirstResponder];
            [self textAll:NO];
            return;
         }
    }
}
展开阅读全文

没有更多推荐了,返回首页