UISearchBar_分类添加maskView属性

在使用UISearchBar时,希望在键盘上方,searchBar下方出现黑色的遮罩,方便点击退去键盘。


UISearchBar_分类添加maskView属性_第1张图片
这里写图片描述
  以往是自定义searchBar,再实现相应的方法。使用的时候也需要用自定义的,
相对更麻烦些。因此,利用runTime为UISearchBar的分类添加maskView功能。

完整代码链接:https://github.com/xinyuly/UISearchBar-MaskView
使用:将#import "UISearchBar+MaskView.h" 导入需要的地方即可。
部分代码:

@implementation UISearchBar (MaskView)
#pragma mark - UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    [self showMaskView];
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    [self removeMaskView];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    return YES;
}
//动态添加
- (MaskView *)_maskView {
    MaskView *maskView = (MaskView *)objc_getAssociatedObject(self, XYMaskViewKey);
    if (maskView == nil) {
        maskView = [[MaskView alloc] init];
        [maskView setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.6]];
        objc_setAssociatedObject(self, XYMaskViewKey, maskView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return maskView;
}

@end

你可能感兴趣的:(UISearchBar_分类添加maskView属性)