标签:
默认情况下,苹果给我们的搜索框??并不是我们想要的效果,所以我们可能就需要去自定义一个自己需要的搜索框,下面简单写一个自定义的控件。
要注意:
1、searchIcon.height = 30;这里的控件尺寸直接赋值是因为在头文件中引入UIView的类别 :http://www.cnblogs.com/daomul/p/4662402.html
2、采用instancetype单例模式加载控件
3、leftView是左边的一个??图片,contentMode是图片控件的填充方式,为了使得图片居中显示
4、是基于UITextField的
5、那么我们在我们对应父控制器中就可以通过如下代码调用:
//自定义搜索框
XBSearchBar *searchBar = [XBSearchBar searchBar];
searchBar.width = 300;
searchBar.height = 30;
//设置为navigation的正中位置
self.navigationItem.titleView = searchBar;
头文件代码:
// // XBSearchBar.h // XibaTest // // Created by bos on 15-6-14. // Copyright (c) 2015年 axiba. All rights reserved. // #import <UIKit/UIKit.h> @interface XBSearchBar : UITextField +(instancetype)searchBar; @end
文件代码:
1 // 2 // XBSearchBar.m 3 // XibaTest 4 // 5 // Created by bos on 15-6-14. 6 // Copyright (c) 2015年 axiba. All rights reserved. 7 // 8 9 #import "XBSearchBar.h" 10 11 @implementation XBSearchBar 12 13 -(id)initWithFrame:(CGRect)frame 14 { 15 self = [super initWithFrame:frame]; 16 17 if (self) { 18 19 self.font = [UIFont systemFontOfSize:15]; 20 self.placeholder = @"请输入搜索条件..."; 21 self.background = [UIImage imageNamed:@"searchbar_textfield_background"]; 22 23 UIImageView *searchIcon = [[UIImageView alloc]init]; 24 searchIcon.height = 30; 25 searchIcon.width = 30; 26 //控制图片控件内部的填充方式 27 searchIcon.contentMode = UIViewContentModeCenter; 28 searchIcon.image = [UIImage imageNamed:@"searchbar_textfield_search_icon"]; 29 30 self.leftView = searchIcon; 31 self.leftViewMode = UITextFieldViewModeAlways; 32 33 } 34 return self; 35 } 36 37 +(instancetype)searchBar 38 { 39 return [[self alloc]init]; 40 } 41 42 /* 43 // Only override drawRect: if you perform custom drawing. 44 // An empty implementation adversely affects performance during animation. 45 - (void)drawRect:(CGRect)rect { 46 // Drawing code 47 } 48 */ 49 50 @end
标签:
原文地址:http://www.cnblogs.com/daomul/p/4662422.html