//搜索框
UISearchBar *searchBar = [[UISearchBar alloc] init];
// searchBar.delegate = self;
searchBar.frame = CGRectMake(10, 0, screenW-80, titleView.bounds.size.height);
searchBar.layer.cornerRadius = 17;
searchBar.layer.masksToBounds = YES;
[searchBar.layer setBorderWidth:8];
[searchBar.layer setBorderColor:[UIColor whiteColor].CGColor]; //設置邊框為白色
searchBar.placeholder = @"請輸入目的地";
searchBar.translucent = YES;
searchBar.searchBarStyle = UISearchBarStyleProminent;
//改變占位符的字體大小顏色
UITextField * searchField = [searchBar valueForKey:@"_searchField"];
[searchField setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
[searchField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
//改變左邊搜索圖標坐標位置。后面的占位符蘋果已經(jīng)做好約束總是跟隨在搜索??圖標后面。
[searchBar setPositionAdjustment:UIOffsetMake(60, 0) forSearchBarIcon:UISearchBarIconSearch];
設置搜索欄中圖片的位置偏移,圖片的枚舉如下:
typedef NS_ENUM(NSInteger, UISearchBarIcon) {
UISearchBarIconSearch, //搜索圖標
UISearchBarIconClear, // 清除圖標
UISearchBarIconBookmark, // 書本圖標
UISearchBarIconResultsList, // 結果列表圖標
};
下面是搜索框控件的一些代理方法:
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar;
將要開始編輯時的回調(diào),返回為NO,則不能編輯
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar;
已經(jīng)開始編輯時的回調(diào)
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar;
將要結束編輯時的回調(diào)
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar;
已經(jīng)結束編輯的回調(diào)
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText; 編輯文字改變的回調(diào)
- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text ;
編輯文字改變前的回調(diào),返回NO則不能加入新的編輯文字
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar;
搜索按鈕點擊的回調(diào)
- (void)searchBarBookmarkButtonClicked:(UISearchBar *)searchBar;
書本按鈕點擊的回調(diào)
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar;
取消按鈕點擊的回調(diào)
- (void)searchBarResultsListButtonClicked:(UISearchBar *)searchBar;
搜索結果按鈕點擊的回調(diào)
- (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope;
搜索欄的附加試圖中切換按鈕觸發(fā)的回調(diào)

D7C05039-1BCD-40EA-801F-F3BD6C8CDE41.png