默認狀況下,蘋果給咱們的搜索框🔍並非咱們想要的效果,因此咱們可能就須要去自定義一個本身須要的搜索框,下面簡單寫一個自定義的控件。html
要注意:ide
一、searchIcon.height = 30;這裏的控件尺寸直接賦值是由於在頭文件中引入UIView的類別 :http://www.cnblogs.com/daomul/p/4662402.htmlspa
二、採用instancetype單例模式加載控件code
三、leftView是左邊的一個🔍圖片,contentMode是圖片控件的填充方式,爲了使得圖片居中顯示orm
四、是基於UITextField的htm
五、那麼咱們在咱們對應父控制器中就能夠經過以下代碼調用:blog
//自定義搜索框圖片
XBSearchBar *searchBar = [XBSearchBar searchBar];animation
searchBar.width = 300;it
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