UIAlertController 实现UITextField校验(点击确认不消失)

效果图

UIAlertController 点击确认时候会消失,无法校验是否输入,所以在他dismiss前要先做校验

通过小技巧(点击确认在block中添加一个数组,使其崩溃)找到以下两个方法(系统版本不同)

_dismissAnimated:triggeringAction:triggeredByPopoverDimmingView:dismissCompletion:
_dismissAnimated:triggeringAction:triggeredByPopoverDimmingView:

hook掉以上两个方法

#import 

#pragma mark - Private

+ (void)load {
    
    SEL originalSelector = nil;
    SEL swizzledSelector = nil;
    
    // _dismissAnimated
    originalSelector = NSSelectorFromString(@"_dismissAnimated:triggeringAction:triggeredByPopoverDimmingView:dismissCompletion:");
    swizzledSelector = @selector(tm_dismissAnimated:triggeringAction:triggeredByPopoverDimmingView:dismissCompletion:);
    [UIAlertController jr_swizzleMethod:originalSelector withMethod:swizzledSelector error:nil];
    
    originalSelector = NSSelectorFromString(@"_dismissAnimated:triggeringAction:triggeredByPopoverDimmingView:");
    swizzledSelector = @selector(tm_dismissAnimated:triggeringAction:triggeredByPopoverDimmingView:);
    [UIAlertController jr_swizzleMethod:originalSelector withMethod:swizzledSelector error:nil];
}

- (void)tm_dismissAnimated:(BOOL)flag triggeringAction:(UIAlertAction *)action triggeredByPopoverDimmingView:(id)view dismissCompletion:(void (^)(void))completion {
    // 保证点击取消依旧可以消失
    if (action.style != UIAlertActionStyleCancel) {
        for (UITextField *textField in self.textFields) {
            if ([textField.text isEqualToString:@""]) {
                [textField placeholderShake]; // placeholder 抖动动画
                return;
            }
        }
    }
    
    [self tm_dismissAnimated:flag triggeringAction:action triggeredByPopoverDimmingView:view dismissCompletion:completion];
}

- (void)tm_dismissAnimated:(BOOL)flag triggeringAction:(UIAlertAction *)action triggeredByPopoverDimmingView:(id)view {
    // 保证点击取消依旧可以消失
    if (action.style != UIAlertActionStyleCancel) {
        for (UITextField *textField in self.textFields) {
            if ([textField.text isEqualToString:@""]) {
                [textField placeholderShake]; // placeholder 抖动动画
                return;
            }
        }
    }
    
    [self tm_dismissAnimated:flag triggeringAction:action triggeredByPopoverDimmingView:view];
}

你可能感兴趣的:(UIAlertController 实现UITextField校验(点击确认不消失))