您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 開發:在 navigationItem 中加入搜尋欄

編輯:iOS 開發綜合

許多 App 會在導覽列上放置搜尋欄,讓使用者能快速搜尋內容。在 iOS 中,可以建立 UISearchBar,再包裝成 UIBarButtonItem,指定給 navigationItem。

建立搜尋欄

UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 200, 28)];
searchBar.backgroundImage = [UIImage imageNamed:@"btu_search"];
searchBar.placeholder = @"搜索";
searchBar.delegate = self;

放入導覽列

UIBarButtonItem *searchButton = [[UIBarButtonItem alloc] initWithCustomView:searchBar];
self.navigationItem.rightBarButtonItems = [NSArray arrayWithObject:searchButton];

處理搜尋事件

完成 UI 配置後,只要在 UISearchBarDelegate 的 searchBarSearchButtonClicked 方法中實作搜尋邏輯即可。

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    NSString *keyword = searchBar.text;
    // 依 keyword 執行搜尋
}

這種做法簡單易用,也能與現有導覽列樣式自然整合。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved