在實際開發中,搜索框的樣式多種多樣,iOS 中原生的搜索框有許多UI 會進行修改。所以在項目中,自己進行自定義,你會用到的額。直接用吧。更多文章,也可以關注新浪博客http://blog.sina.com.cn/resoftios。
//
//?ZJSearchBar.h
//?ZJSearchBar
//
//?Created by張建on2017/4/22.
//?Copyright ? 2017年張建. All rightsreserved.
//
#import
//自定義UISearchBar,方便項目中的使用。后續可自行進行功能添加。
@interfaceZJSearchBar :UISearchBar
//搜索框
@property(nonatomic,strong)UITextField*searchBarTF;
//搜索框的背景,默認是灰色哦。系統色.是否隱藏顯示
@property(nonatomic,assign)BOOLhideSearchBarBackgroundImage;
//輸入框中自定義的光標顏色
@property(nonatomic,strong)UIColor*cursorColor;
//輸入框中清除按鈕的圖片
@property(nonatomic,strong)UIImage*clearButtonImage;
//取消按鈕(當showCancleButton= YES時,才可以得到)
@property(nonatomic,strong)UIButton*cancleButton;
//設置輸入框中??和提示文字是否居中。(NO是不居中)
@property(nonatomic,assign,setter=setHasCentredPlaceholder:)BOOLhasCentredPlaceholder;
//
//?ZJSearchBar.m
//?ZJSearchBar
//
//?Created by張建on2017/4/22.
//?Copyright ? 2017年張建. All rightsreserved.
//
#import"ZJSearchBar.h"
@implementationZJSearchBar
//設置輸入框
-(UITextField*)searchBarTF{
//獲取輸入框
_searchBarTF=[selfvalueForKey:@"searchField"];
return_searchBarTF;
}
//設置輸入框中的光標的顏色,可以自定義的哦
-(void)setCursorColor:(UIColor*)cursorColor{
if(cursorColor){
_cursorColor=cursorColor;
//1.獲取輸入框
UITextField*searchField =self.searchBarTF;
if(searchField){
//2.光標顏色
[searchFieldsetTintColor:cursorColor];
}
}
}
//設置清除按鈕的圖標
-(void)setClearButtonImage:(UIImage*)clearButtonImage{
if(clearButtonImage){
_clearButtonImage=clearButtonImage;
//1.獲取輸入框
UITextField*searchField =self.searchBarTF;
if(searchField){
//清除按鈕的圖片
UIButton*button =[searchFieldvalueForKey:@"_clearButton"];
[buttonsetImage:clearButtonImageforState:UIControlStateNormal];
searchField.clearButtonMode=UITextFieldViewModeWhileEditing;
}
}
}
//隱藏背景圖
-(void)setHideSearchBarBackgroundImage:(BOOL)hideSearchBarBackgroundImage{
if(hideSearchBarBackgroundImage){
_hideSearchBarBackgroundImage=hideSearchBarBackgroundImage;
self.backgroundImage=[[UIImagealloc]init];
}
}
//獲取取消的按鈕
-(UIButton*)cancleButton{
self.showsCancelButton=YES;
for(UIView*viewin[[self.subviewslastObject]subviews]){
if([viewisKindOfClass:[UIButtonclass]]){
_cancleButton=(UIButton*)view;
}
}
return_cancleButton;
}
-(instancetype)initWithFrame:(CGRect)frame
{
if((self=[superinitWithFrame:frame]))
{
self.hasCentredPlaceholder=YES;
}
returnself;
}
//設置搜索框中搜索??和提示文字的位置(居左)
-(void)setHasCentredPlaceholder:(BOOL)hasCentredPlaceholder
{
_hasCentredPlaceholder=hasCentredPlaceholder;
SELcenterSelector=NSSelectorFromString([NSStringstringWithFormat:@"%@%@",@"setCenter",@"Placeholder:"]);
if([selfrespondsToSelector:centerSelector])
{
NSMethodSignature*signature =[[UISearchBarclass]instanceMethodSignatureForSelector:centerSelector];
NSInvocation*invocation =[NSInvocationinvocationWithMethodSignature:signature];
[invocationsetTarget:self];
[invocationsetSelector:centerSelector];
[invocationsetArgument:&_hasCentredPlaceholderatIndex:2];
[invocationinvoke];
}
}