1. 程式人生 > 其它 >iOS中在導航條設定搜尋框使用小結

iOS中在導航條設定搜尋框使用小結

  最近在專案開發中用到了搜尋框,一般是設定在列表頂部或者導航條上。下面說一下在導航條上使用搜索框的思路,剛開始是直接將CCSearchBar新增到導航條,在viewWillDisappear設定隱藏,在viewWillAppear中設定可見,結果在蘋果X上出現頁面卡頓的情況。原因可能是進入頁面的時候獲取焦點,

也可能是狀態列高度設定不準確,總之這個方案會有點問題。我們換另外一個思路,將導航條設定為titleview,這裡需要特別注意,如果直接將CCSearchBar賦值給self.navigationItem.titleView,搜尋框的長度會不受控制,需要封裝一層,將搜尋框新增到一個view中,然後將該view賦值給titleview。

  

- (CCSearchBar *)searchBar{

if (!_searchBar) {

_searchBar = [[CCSearchBar alloc]init];

_searchBar.backgroundColor = [UIColor clearColor];

_searchBar.textfiledBgColor = K_CC_GRAY_BG_COLOR;

_searchBar.placeholder = K_CC_LOCAL_STR(@"home.search");

_searchBar.placeHolderFontSize = 14;

_searchBar.placeHolderTextColor = K_CC_TEXT_GRAY_COLOR;

_searchBar.textPosition = SearchBarTextPositionCenter;

_searchBar.textColor = K_CC_COLOR_STRING(@"17315C");

_searchBar.frame = CGRectMake(0, 5, K_CC_SCREEN_WIDTH-146, 34);

_searchBar.delegate = self;

}

return _searchBar;

}

- (UIView *)toolSearch

{

if (!_toolSearch) {

_toolSearch=[[UIView alloc]initWithFrame:CGRectMake(0, 0, K_CC_SCREEN_WIDTH - 106, 44)];

_toolSearch.backgroundColor = [UIColor clearColor];

[_toolSearch addSubview:self.searchBar];

}

return _toolSearch;

}

self.navigationItem.titleView=self.toolSearch;

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

[self.searchBar becomeFirstResponder];

});