iOS UISearchBar 封装 自定义UISearchBar 含iOS11适配,可以说UISearchBar看我就够了~

鉴于UISearchBar样式修改不好操作,以及它的一些系统默认处理不符合实际产品需求,和iOS 11之后UISearchBar的placeholder居中问题跟之前版本不一样,特此封装了一个UISearchBar的子类,以后用的时候直接拿来用就方便多了。附上地址项目地址

先总结:本demo封装、修改的内容

1、 UISearchBar 样式

2、iOS11之前placeholder文字默认是居左的,iOS 11默认居中的,为了样式统一,且两个样式都支持,做了一下封装。只要继承该控件,控件内部已经实现placeholder居中和居左方案。

3、UISearchBar 的clearBtn的显示方式

4、取消按钮的title 文字内容、颜色

5、UISearchBar当失去焦点时,系统会把取消按钮的enable设为no,这样点击取消按钮的时候默认输入框会获得焦点,而不是取消搜索,实际应用中很少这样用,所以封装的控件中对改功能做了支持,既可以支持原系统默认事件,亦可以直接响应取消事件。

具体支持哪些修改,详见头文件

@interfaceFLJSearchBar :UISearchBar

/**

 这里根据实际应用来做的封装,一般情况都是 UITextFieldViewModeWhileEditing和UITextFieldViewModeNever

 yes-UITextFieldViewModeNever    no-UITextFieldViewModeWhileEditing

 默认 no

 */

@property(nonatomic,assign)BOOL clearBtnHidden;

//placeHolder 是否居中 iOS11之前默认是居中的 iOS11之后居左

@property(nonatomic,assign)BOOL placeHolderCenter;

//placeHolder文字

@property(nonatomic,copy)NSString* placeHolderString;

//placeHolder字号 默认16 和输入框文字字号一样

@property(nonatomic,strong)UIFont* placeHolderStringFont;

//placeHolder文字颜色

@property(nonatomic,strong)UIColor* placeHolderStringColor;

//取消按钮文字  系统默认cancel,这里默认 取消

@property(nonatomic,copy)NSString* cancelBtnTitle;

//取消按钮文字颜色

@property(nonatomic,strong)UIColor* cancelBtnTitleColor;

//圆角

@property(nonatomic,assign)CGFloat cornerRadius;

//边框颜色

@property(nonatomic,strong)UIColor* borderColor;

//边框宽度

@property(nonatomic,assign)CGFloat borderWidth;

//记录默认情况下的搜索图片偏移

@property(nonatomic,assign)UIOffsetoriginPositionSearchOffSet;

//系统searchbar,如果search没有获得焦点,点击取消默认会获得焦点(而不会响应取消事件)

//cancelInputDisabled yes 直接响应取消事件

@property(nonatomic,assign)BOOL cancelInputDisabled;


.m实现

#import "FLJSearchBar.h"

#import "UIImage+Extension.h"

#define kDefaultBorderColor [UIColor colorWithRed:(225)/255.0green:(226)/255.0blue:(227)/255.0alpha:1.0]

#define kDefaultPlaceHolderTextFont [UIFont systemFontOfSize:16]

#define kDefaultPlaceHolerTextColor [UIColor colorWithRed:(187)/255.0green:(187)/255.0blue:(187)/255.0alpha:1.0]

#define kDefaultCancelBtnTitleFont [UIFont systemFontOfSize:16]

#define kDefaultCancelBtnTitleColor [UIColor colorWithRed:(102)/255.0green:(102)/255.0blue:(102)/255.0alpha:1.0]

@interface FLJSearchBar ()

@property(nonatomic,assign)BOOL hideClearBtn;

@end

@implementation FLJSearchBar

-(instancetype)initWithFrame:(CGRect)frame

{

    if(self== [superinitWithFrame:frame]) {

        [self setBackgroundColor:[UIColor whiteColor]];

        //cancel按钮显示

        self.showsCancelButton = YES;

        //光标颜色tintColor

//        self.tintColor = [UIColor clearColor];

        self.backgroundImage = [UIImage imageWithColor:[UIColor whiteColor] size:CGSizeMake(100, self.bounds.size.height)];

        [self setImage:[UIImage imageNamed:@"icon_search"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];

        [self setImage:[UIImage imageNamed:@"icon_search_clear"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal];

        //ios11 之前这个高度决定textfield高度 默认28

        [self setSearchFieldBackgroundImage:[UIImage imageWithColor:[UIColor clearColor] size:CGSizeMake(100, self.bounds.size.height)] forState:UIControlStateNormal];


        self.originPositionSearchOffSet = UIOffsetMake(10, 0);

        //搜索图标偏移

        [self setPositionAdjustment:self.originPositionSearchOffSet forSearchBarIcon:UISearchBarIconSearch];

        //清除按钮偏移向左偏移10

        [self setPositionAdjustment:UIOffsetMake(-10, 0) forSearchBarIcon:UISearchBarIconClear];

        //整个输入框(textfield)的偏移量

//        [self setSearchFieldBackgroundPositionAdjustment:UIOffsetMake(10, 0)];

        //文字距离搜索图标的偏移,默认是紧挨着的

        [self setSearchTextPositionAdjustment:UIOffsetMake(10, 0)];


        self.placeHolderString = @"请输入搜索内容";

        self.cornerRadius=self.bounds.size.height/2.f;

        self.borderWidth=1.f;

        self.borderColor = kDefaultBorderColor;

        self.placeHolderCenter = NO;

        [self setCancelBtnTitle:@"取消"];

    }

    return self;

}

#pragma mark  setter & getter

/**

 设置placeHolder

 @param placeHolderString placeHolder

 */

-(void)setPlaceHolderString:(NSString*)placeHolderString

{

    _placeHolderString= [placeHolderStringcopy];

    UITextField*textField = [selftextField];

    if(textField) {

        textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:_placeHolderString attributes:@{NSForegroundColorAttributeName:_placeHolderStringColor?_placeHolderStringColor:kDefaultPlaceHolerTextColor,NSFontAttributeName:_placeHolderStringFont?_placeHolderStringFont:kDefaultPlaceHolderTextFont}];

    }

}

/**

 设置placeHolder字号

 @param placeHolderStringFont 字号

 */

-(void)setPlaceHolderStringFont:(UIFont*)placeHolderStringFont

{

    _placeHolderStringFont= placeHolderStringFont;

    UITextField*textField = [selftextField];

    if(textField) {

        textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:_placeHolderString attributes:@{NSForegroundColorAttributeName:_placeHolderStringColor?_placeHolderStringColor:kDefaultPlaceHolerTextColor,NSFontAttributeName:_placeHolderStringFont}];

        textField.font = _placeHolderStringFont;

    }

}

/**

 设置placehHolder字体颜色

 @param placeHolderStringColor placehHolder字体颜色

 */

-(void)setPlaceHolderStringColor:(UIColor*)placeHolderStringColor

{

    _placeHolderStringColor= placeHolderStringColor;


    UITextField*textField = [selftextField];

    if(textField) {

        textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:_placeHolderString attributes:@{NSForegroundColorAttributeName:_placeHolderStringColor,NSFontAttributeName:_placeHolderStringFont?_placeHolderStringFont:kDefaultPlaceHolderTextFont}];

    }

}

/**

 设置取消按钮文字

 */

-(void)setCancelBtnTitle:(NSString*)cancelBtnTitle

{

    _cancelBtnTitle= [cancelBtnTitlecopy];

    UIButton*cancel = [selfcancelBtn];

    if(cancel) {

        [cancelsetTitle:cancelBtnTitle forState:UIControlStateNormal];


        if (!self.cancelBtnTitleColor) {

            [cancelsetTitleColor:kDefaultCancelBtnTitleColor forState:UIControlStateNormal];

        }

        cancel.titleLabel.font = kDefaultCancelBtnTitleFont;

    }

}

/**

 设置取消按钮文字颜色

 */

-(void)setCancelBtnTitleColor:(UIColor*)cancelBtnTitleColor

{

    _cancelBtnTitleColor= cancelBtnTitleColor;

    UIButton*cancel = [selfcancelBtn];

    if(cancel) {

        [cancelsetTitleColor:_cancelBtnTitleColor forState:UIControlStateNormal];

    }

}

/**

 隐藏清除按钮

 @param clearBtnHidden yes隐藏 no输入的时候显示

 */

-(void)setClearBtnHidden:(BOOL)clearBtnHidden

{

    _clearBtnHidden= clearBtnHidden;

    self.hideClearBtn = _clearBtnHidden;

}

-(void)setHideClearBtn:(BOOL)hideClearBtn

{

    _hideClearBtn= hideClearBtn;

    UITextField*textField = [selftextField];

    if(textField) {

        if (_hideClearBtn) {

            textField.clearButtonMode=UITextFieldViewModeNever;

        }else

            textField.clearButtonMode = UITextFieldViewModeWhileEditing;

    }

}

/**

 设置搜索框圆角

 */

-(void)setCornerRadius:(CGFloat)cornerRadius

{

    _cornerRadius= cornerRadius;

    UITextField*textField = [selftextField];

    if(textField) {

        textField.layer.cornerRadius=_cornerRadius;

        textField.layer.masksToBounds=YES;

        textField.clipsToBounds=YES;

    }

}

/**

 设置搜索框边框颜色

 */

-(void)setBorderColor:(UIColor*)borderColor

{

    _borderColor= borderColor;

    UITextField*textField = [selftextField];

    if(textField) {

        textField.layer.borderColor= borderColor.CGColor;

    }

}

/**

 设置搜索框边框 宽度

 */

-(void)setBorderWidth:(CGFloat)borderWidth

{

    _borderWidth= borderWidth;

    UITextField*textField = [selftextField];

    if(textField) {

        textField.layer.borderWidth= borderWidth;

        textField.layer.masksToBounds=YES;

    }

}

/**

 设置placeholder是否居中显示

 */

- (void)setPlaceHolderCenter:(BOOL)placeHolderCenter

{

    _placeHolderCenter= placeHolderCenter;


    if(@available(iOS11.0, *)) {

        UITextField* textField = [selftextField];

        textField.delegate=self;

        if (_placeHolderCenter) {

            [self setPositionAdjustment:UIOffsetMake((textField.frame.size.width-[self placeHolderTextWidth])/2, 0) forSearchBarIcon:UISearchBarIconSearch];

        }else

            [self setPositionAdjustment:self.originPositionSearchOffSet forSearchBarIcon:UISearchBarIconSearch];

    }else

    {

        SELcenterSelector =NSSelectorFromString([NSStringstringWithFormat:@"%@%@",@"setCenter",@"Placeholder:"]);

        if([selfrespondsToSelector:centerSelector])

        {

//方法1         [self setValue:@(_placeHolderCenter) forKeyPath:@"centerPlaceholder"];

//方法2

            NSMethodSignature*signature = [[UISearchBarclass]instanceMethodSignatureForSelector:centerSelector];

            NSInvocation*invocation = [NSInvocationinvocationWithMethodSignature:signature];

            [invocationsetTarget:self];

            [invocationsetSelector:centerSelector];

            [invocationsetArgument:&_placeHolderCenteratIndex:2];

            [invocationinvoke];

        }

    }

}

/**

 设置当输入框没有获得焦点时,点击取消按钮是否直接响应取消事件,而不是响应输入事件

 */

-(void)setCancelInputDisabled:(BOOL)cancelInputDisabled

{

    _cancelInputDisabled= cancelInputDisabled;

    UIButton*cancelBtn = [selfcancelBtn];

    cancelBtn.enabled=YES;

}

#pragma mark UITextFieldDelegate

#warning 实现这两个代理方法后 searchbar的textFieldShouldBeginEditing 和textFieldShouldEndEditing将不执行 需要代理调起方法

-(BOOL)textFieldShouldBeginEditing:(UITextField*)textField

{

    if([self.delegaterespondsToSelector:@selector(searchBarShouldBeginEditing:)]) {

       BOOL begin = [self.delegate searchBarShouldBeginEditing:self];

        if(begin) {

            if(@available(iOS11.0, *) &&self.placeHolderCenter) {

                [self setPositionAdjustment:self.originPositionSearchOffSet forSearchBarIcon:UISearchBarIconSearch];

            }

            if(!self.clearBtnHidden) {

                self.hideClearBtn=NO;

            }

        }

        returnbegin;

    }


    if(@available(iOS11.0, *) &&self.placeHolderCenter) {

        [self setPositionAdjustment:self.originPositionSearchOffSet forSearchBarIcon:UISearchBarIconSearch];

    }

    if (!self.clearBtnHidden) {

        self.hideClearBtn=NO;

    }

    return YES;

}

-(BOOL)textFieldShouldEndEditing:(UITextField*)textField

{

    if([self.delegaterespondsToSelector:@selector(searchBarShouldEndEditing:)]){

        BOOL end = [self.delegate searchBarShouldEndEditing:self];


        if(end) {

            if(@available(iOS11.0, *) &&self.placeHolderCenter) {

                if(textField.text.length==0) {

                    [self setPositionAdjustment:UIOffsetMake((textField.frame.size.width-[self placeHolderTextWidth])/2, 0) forSearchBarIcon:UISearchBarIconSearch];

                }

            }

            if(self.clearBtnHidden) {

                self.hideClearBtn=YES;

            }

        }

        returnend;

    }


    if(@available(iOS11.0, *) &&self.placeHolderCenter) {

        if(textField.text.length==0) {

            [self setPositionAdjustment:UIOffsetMake((textField.frame.size.width-[self placeHolderTextWidth])/2, 0) forSearchBarIcon:UISearchBarIconSearch];

        }

    }

    if (self.clearBtnHidden) {

        self.hideClearBtn=YES;

    }

    return YES;

}

-(void)textFieldDidEndEditing:(UITextField*)textField

{

    if (self.cancelInputDisabled) {

        self.cancelInputDisabled = YES;

    }

}

/**

 获得搜索框

 */

-(UITextField*)textField

{

    UITextField*searchField = [selfvalueForKey:@"searchField"];


    //    for (UIView *view in self.subviews.lastObject.subviews) {

    //        if([view isKindOfClass:NSClassFromString(@"UISearchBarTextField")]) {

    //            return (UITextField*)view;

    //        }

    //    }

    returnsearchField;

}

/**

 获得取消按钮

 */

-(UIButton*)cancelBtn

{

    UIView* view = [selfvalueForKeyPath:@"cancelButton"];

    //    if ([view isKindOfClass:NSClassFromString(@"UINavigationButton")]) {

    UIButton*cancelBtn = (UIButton*)view;

    //    }

    returncancelBtn;

}

/**

 计算placeHolder的宽度

 */

-(CGFloat)placeHolderTextWidth

{

    UITextField* textField = [selftextField];

    return [self.placeHolderString boundingRectWithSize:textField.frame.size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSForegroundColorAttributeName:_placeHolderStringColor?_placeHolderStringColor:kDefaultPlaceHolerTextColor,NSFontAttributeName:_placeHolderStringFont?_placeHolderStringFont:kDefaultPlaceHolderTextFont} context:nil].size.width;

}

-(void)layoutSubviews

{

    [super layoutSubviews];

    if(@available(iOS11.0, *) &&self.placeHolderCenter) {

        UITextField* textField = [selftextField];

        [self setPositionAdjustment:UIOffsetMake((textField.frame.size.width-[self placeHolderTextWidth])/2, 0) forSearchBarIcon:UISearchBarIconSearch];

    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,050评论 4 370
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,538评论 1 306
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 111,673评论 0 254
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,622评论 0 218
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,047评论 3 295
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,974评论 1 224
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,129评论 2 317
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,893评论 0 209
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,654评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,828评论 2 254
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,297评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,619评论 3 262
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,326评论 3 243
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,176评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,975评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,118评论 2 285
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,909评论 2 278

推荐阅读更多精彩内容