在使用UISearchBar時,希望在鍵盤上方,searchBar下方出現(xiàn)黑色的遮罩,方便點擊退去鍵盤。
這里寫圖片描述
以往是自定義searchBar,再實現(xiàn)相應的方法。使用的時候也需要用自定義的,
相對更麻煩些。因此,利用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;
}
//動態(tài)添加
- (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