標籤:
TextField作為搜尋方塊的使用
在iOS開發中我們經常會使用到搜尋方塊,但是有的時候系統內建的搜尋方塊不足以滿足我嗎想要的功能,這個時候我們就可以使用自訂的搜尋方塊實現想要的功能。
今天就簡單的介紹一下怎麼去使用UITextField實現一個搜尋方塊,當然如果你有更好的方法也可以分享出來,大家相互學習。
一:直接使用
1 UITextField *text = [[UITextField alloc] init]; 2 text.frame = CGRectMake(0, 0, 320, 30); 3 text.background = [UIImage resizeImage:@"searchbar_textfield_background"]; 4 //文字垂直置中 5 text.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; 6 //搜尋表徵圖 7 UIImageView *view = [[UIImageView alloc] init]; 8 view.image = [UIImage resizeImage:@"searchbar_textfield_search_icon"]; 9 view.frame = CGRectMake(0, 0, 35, 35);10 //左邊搜尋表徵圖的模式11 view.contentMode = UIViewContentModeCenter;12 text.leftView = view;13 //左邊搜尋表徵圖總是顯示14 text.leftViewMode = UITextFieldViewModeAlways;15 //右邊刪除所有表徵圖16 text.clearButtonMode = UITextFieldViewModeAlways;17 18 self.navigationItem.titleView = text;
二:封裝
1 //初始化 2 /** 3 * 使用TextField實現搜尋方塊功能封裝 4 */ 5 //設定字型大小 6 self.font = [UIFont systemFontOfSize:15]; 7 //設定提示文字 8 self.placeholder = @"請輸入搜尋條件"; 9 //設定文字框的背景圖片(使用分類實現展開效果)10 self.background = [UIImage resizeImage:@"searchbar_textfield_background"];11 //文字垂直置中12 self.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;13 //搜尋表徵圖14 UIImageView *view = [[UIImageView alloc] init];15 //設定圖片控制器的的圖片16 view.image = [UIImage resizeImage:@"searchbar_textfield_search_icon"];17 //設定圖片的frame18 view.width = 30;19 view.height = 30;20 //左邊搜尋表徵圖的模式21 view.contentMode = UIViewContentModeCenter;22 self.leftView = view;23 //左邊搜尋表徵圖總是顯示24 self.leftViewMode = UITextFieldViewModeAlways;25 //右邊刪除所有表徵圖26 self.clearButtonMode = UITextFieldViewModeAlways;
/**使用一:
* 使用封裝好的SearchBar
*/
1 iCocosSearchBar *searchbar = [iCocosSearchBar searchBar];2 searchbar.width = 300;3 searchbar.height = 30;4 self.navigationItem.titleView = searchbar;
/**使用二
* 使用封裝好的SearchBar
*/
1 iCocosSearchBar *searchbar = [iCocosSearchBar searchBar];2 searchbar.width = 300;3 searchbar.height = 30;4 [self.view addSubview:searchbar];
iOS開發——UI篇OC篇&TextField作為搜尋方塊的使用