iOS开发基础66-搜索功能深度解析:UISearchBar、UISearchController 与导航栏搜索
iOS 搜索功能深度解析:UISearchBar、UISearchController 与导航栏搜索
本文系统梳理 iOS 搜索功能:UISearchBar 的常用属性与代理方法、inputAccessoryView 遮盖视图、传统搜索框实现;以及现代推荐方案——UISearchController(iOS 8+,自带搜索结果控制器与状态管理)、导航栏集成搜索(iOS 11+ navigationItem.searchController)、iOS 13+ UISearchTextField 直接自定义、实时搜索过滤。
一、UISearchBar 简介
UISearchBar 是 UIKit 提供的搜索输入控件,集成了输入框、取消按钮、书签按钮、搜索结果按钮、分栏条(Scope Bar)等子控件,便于快速实现搜索功能。
现代推荐:iOS 8+ 引入了
UISearchController,它封装了 UISearchBar 和搜索状态管理,自带搜索结果控制器、自动显示/隐藏取消按钮、动画过渡等,是实现搜索功能的首选方案。纯 UISearchBar 适合简单场景或需要高度自定义的场景。
二、UISearchBar 常用属性
#import <UIKit/UIKit.h>
@interface ViewController () <UISearchBarDelegate>
@property (nonatomic, strong) UISearchBar *searchBar;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 初始化
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectZero];
[self.searchBar sizeToFit];
// 占位符
self.searchBar.placeholder = @"搜索";
// 顶部提示文本(显示在搜索框上方)
self.searchBar.prompt = @"请输入关键词";
// 搜索框样式(注意:barStyle 类型是 UIBarStyle,不是 UIBarMetrics)
self.searchBar.barStyle = UIBarStyleDefault; // 默认
// self.searchBar.barStyle = UIBarStyleBlack; // 黑色
// 光标颜色和按钮颜色
self.searchBar.tintColor = [UIColor systemBlueColor];
// 是否半透明
self.searchBar.translucent = YES;
// 背景图片(需指定 barMetrics)
[self.searchBar setBackgroundImage:[UIImage imageNamed:@"search_bg"] forBarMetrics:UIBarMetricsDefault];
// 输入框背景图片(不同状态)
[self.searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"field_normal"] forState:UIControlStateNormal];
[self.searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"field_highlighted"] forState:UIControlStateHighlighted];
// 输入框背景偏移
[self.searchBar setSearchFieldBackgroundPositionAdjustment:UIOffsetMake(0, 0) forBarMetrics:UIBarMetricsDefault];
// 文本偏移
[self.searchBar setSearchTextPositionAdjustment:UIOffsetMake(8, 0) forBarMetrics:UIBarMetricsDefault];
// 输入辅助视图(键盘上方的自定义视图,如"完成"按钮工具条)
self.searchBar.inputAccessoryView = self.keyboardToolBar;
// 键盘类型
self.searchBar.keyboardType = UIKeyboardTypeDefault;
// 分栏条(Scope Bar)
self.searchBar.showsScopeBar = YES;
self.searchBar.scopeButtonTitles = @[@"全部", @"歌手", @"歌曲"];
self.searchBar.selectedScopeButtonIndex = 0;
// 书签按钮
self.searchBar.showsBookmarkButton = YES;
// 搜索结果按钮
self.searchBar.showsSearchResultsButton = YES;
// 取消按钮(在编辑时显示)
[self.searchBar setShowsCancelButton:YES animated:YES];
// 自动纠错和拼写检查
self.searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
self.searchBar.spellCheckingType = UITextSpellCheckingTypeNo;
self.searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
// 设置代理
self.searchBar.delegate = self;
// 作为 tableView 的表头(标准做法,不是 addSubview)
self.tableView.tableHeaderView = self.searchBar;
}
@end
注意:
- 搜索框通常作为
tableView.tableHeaderView,而不是addSubview到 tableView。作为 tableHeaderView 会自动固定在顶部并跟随滚动。
三、重要属性详解
1. inputAccessoryView(输入辅助视图)
当搜索框获得焦点弹出键盘时,inputAccessoryView 会显示在键盘上方,通常用来放"完成"、"收起键盘"等按钮:
// 创建一个带"完成"按钮的工具条
UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 44)];
UIBarButtonItem *flex = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *done = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneClicked)];
toolBar.items = @[flex, done];
self.searchBar.inputAccessoryView = toolBar;
- (void)doneClicked {
[self.searchBar resignFirstResponder];
}
原文用半透明黑色 View 作为遮盖层(点击空白收起键盘),这是另一种常见交互。inputAccessoryView 是键盘上方的工具条,两者用途不同。
2. delegate(UISearchBarDelegate)
UISearchBarDelegate 协议定义了搜索框的各种回调:
@protocol UISearchBarDelegate <UIBarPositioningDelegate>
@optional
// 即将开始编辑
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar;
// 已经开始编辑
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar;
// 即将结束编辑
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar;
// 已经结束编辑
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar;
// 文本变化(实时搜索用这个)
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText;
// 文本即将变化(可用于限制输入字符)
- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
// 点击键盘搜索按钮
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar;
// 点击书签按钮
- (void)searchBarBookmarkButtonClicked:(UISearchBar *)searchBar;
// 点击取消按钮
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar;
// 点击搜索结果按钮
- (void)searchBarResultsListButtonClicked:(UISearchBar *)searchBar;
// 分栏选中变化
- (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope;
@end
常用代理方法示例:
#pragma mark - UISearchBarDelegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
// 开始编辑时显示取消按钮
[searchBar setShowsCancelButton:YES animated:YES];
return YES;
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
// 取消:清空文本、收起键盘、隐藏取消按钮、恢复全部数据
searchBar.text = @"";
[searchBar resignFirstResponder];
[searchBar setShowsCancelButton:NO animated:YES];
[self filterDataWithKeyword:@"" scope:searchBar.selectedScopeButtonIndex];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
// 点击搜索按钮:收起键盘,执行搜索
[searchBar resignFirstResponder];
[self filterDataWithKeyword:searchBar.text scope:searchBar.selectedScopeButtonIndex];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
// 实时搜索:文本每次变化都过滤数据
[self filterDataWithKeyword:searchText scope:searchBar.selectedScopeButtonIndex];
}
- (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope {
// 分栏变化:重新过滤
[self filterDataWithKeyword:searchBar.text scope:selectedScope];
}
四、现代方案:UISearchController(重点推荐)
1. 简介
UISearchController(iOS 8+)是苹果推荐的搜索实现方式,它:
- 自动管理 UISearchBar 的显示/隐藏、取消按钮、第一响应者。
- 自带搜索结果控制器(可单独一个 VC 展示结果)。
- 自动处理搜索状态切换的动画过渡。
- 可集成到导航栏(iOS 11+)。
2. 基本使用(搜索结果在当前 tableView 中过滤)
#import <UIKit/UIKit.h>
@interface SearchViewController : UITableViewController <UISearchResultsUpdating>
@property (nonatomic, strong) UISearchController *searchController;
@property (nonatomic, strong) NSArray *allData; // 全部数据
@property (nonatomic, strong) NSMutableArray *filteredData; // 过滤后数据
@end
@implementation SearchViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 模拟数据
self.allData = @[@"Apple", @"Banana", @"Cherry", @"Date", @"Elderberry"];
self.filteredData = [self.allData mutableCopy];
// 创建 UISearchController
// nil 表示搜索结果就在当前控制器中展示(不单独用结果控制器)
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self; // 实时更新代理
self.searchController.obscuresBackgroundDuringPresentation = NO; // 搜索时不变暗背景(因为在当前列表过滤)
self.searchController.searchBar.placeholder = @"搜索水果";
// iOS 11+:集成到导航栏
if (@available(iOS 11.0, *)) {
self.navigationItem.searchController = self.searchController;
self.navigationItem.hidesSearchBarWhenScrolling = YES; // 滚动时隐藏搜索框
} else {
// iOS 11 之前:放到 tableView 表头
self.tableView.tableHeaderView = self.searchController.searchBar;
}
// 关键:设置 definesPresentationContext,确保搜索框弹出时正确管理控制器层级
self.definesPresentationContext = YES;
}
#pragma mark - UISearchResultsUpdating
// 实时搜索回调(搜索框文本变化或获得/失去焦点时调用)
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
NSString *keyword = searchController.searchBar.text;
[self filterDataWithKeyword:keyword];
[self.tableView reloadData];
}
- (void)filterDataWithKeyword:(NSString *)keyword {
if (keyword.length == 0) {
self.filteredData = [self.allData mutableCopy];
return;
}
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self CONTAINS[c] %@", keyword];
self.filteredData = [[self.allData filteredArrayUsingPredicate:predicate] mutableCopy];
}
#pragma mark - TableView DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.filteredData.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
}
cell.textLabel.text = self.filteredData[indexPath.row];
return cell;
}
@end
3. 使用单独的搜索结果控制器
如果搜索结果页和普通列表页 UI 差异大,可以用单独的结果控制器:
// 创建结果控制器
SearchResultsViewController *resultsVC = [[SearchResultsViewController alloc] init];
// 用结果控制器初始化 UISearchController
self.searchController = [[UISearchController alloc] initWithSearchResultsController:resultsVC];
self.searchController.searchResultsUpdater = resultsVC; // 结果控制器自己实现更新
self.searchController.obscuresBackgroundDuringPresentation = YES; // 搜索时变暗背景(因为弹出了结果控制器)
五、导航栏集成搜索(iOS 11+)
iOS 11+ 支持将搜索框集成到导航栏,自动管理大标题和搜索框的展开/收起:
- (void)viewDidLoad {
[super viewDidLoad];
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.searchController.obscuresBackgroundDuringPresentation = NO;
// 大标题模式
self.navigationController.navigationBar.prefersLargeTitles = YES;
self.navigationItem.largeTitleDisplayMode = UINavigationItemLargeTitleDisplayModeAutomatic;
// 集成搜索框到导航栏
self.navigationItem.searchController = self.searchController;
// 滚动时自动隐藏搜索框(默认 YES)
self.navigationItem.hidesSearchBarWhenScrolling = YES;
self.definesPresentationContext = YES;
}
效果:页面下拉时搜索框随大标题展开,上滑滚动时搜索框自动收起,符合 iOS 系统交互规范。
六、自定义 UISearchBar
1. iOS 13+ 直接访问 UISearchTextField
iOS 13+ 可以通过 searchBar.searchTextField 直接访问输入框,自定义字体、颜色、占位符、清除按钮等,不需要遍历子视图:
if (@available(iOS 13.0, *)) {
UITextField *textField = self.searchBar.searchTextField;
textField.font = [UIFont systemFontOfSize:16];
textField.textColor = [UIColor darkTextColor];
textField.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1.0];
textField.layer.cornerRadius = 10;
textField.layer.masksToBounds = YES;
// 自定义占位符颜色
textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"搜索" attributes:@{NSForegroundColorAttributeName: [UIColor grayColor]}];
// 自定义清除按钮
UIButton *clearButton = [textField valueForKey:@"clearButton"];
[clearButton setImage:[UIImage imageNamed:@"custom_clear"] forState:UIControlStateNormal];
}
2. 自定义取消按钮标题
// 方式一:KVC(最简单,iOS 各版本基本通用)
[self.searchBar setValue:@"取消" forKey:@"cancelButtonText"];
// 方式二:UIAppearance(全局统一)
[[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTitle:@"取消"];
// 方式三:遍历子视图(不推荐,iOS 版本差异大)
// 原文的遍历方式在 iOS 13+ 子视图层级变化后可能失效
KVC 访问
cancelButtonText是公开可用的技巧,不会被 App Store 拒绝。遍历子视图找 UIButton 的方式在不同 iOS 版本上不稳定,不推荐。
3. 修改搜索图标
// 自定义搜索图标(左侧放大镜)
[self.searchBar setImage:[UIImage imageNamed:@"custom_search"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
// 清除按钮图标
[self.searchBar setImage:[UIImage imageNamed:@"custom_clear"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal];
七、实时搜索过滤完整示例
@interface ViewController () <UISearchResultsUpdating>
@property (nonatomic, strong) NSArray *models; // 原始数据模型数组
@property (nonatomic, strong) NSArray *filteredModels; // 过滤后
@end
@implementation ViewController
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
NSString *keyword = searchController.searchBar.text;
if (keyword.length == 0) {
self.filteredModels = self.models;
} else {
// 按 name 属性模糊匹配(不区分大小写)
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS[c] %@", keyword];
self.filteredModels = [self.models filteredArrayUsingPredicate:predicate];
}
[self.tableView reloadData];
}
@end
CONTAINS[c]中的c表示不区分大小写(case-insensitive),d表示不区分变音符号(diacritic-insensitive)。
八、Swift 版本对照
UISearchController(Swift)
import UIKit
class SearchVC: UITableViewController, UISearchResultsUpdating {
var searchController: UISearchController!
var allData = ["Apple", "Banana", "Cherry"]
var filteredData: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
filteredData = allData
searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.placeholder = "搜索"
navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = true
definesPresentationContext = true
}
func updateSearchResults(for searchController: UISearchController) {
let keyword = searchController.searchBar.text ?? ""
if keyword.isEmpty {
filteredData = allData
} else {
filteredData = allData.filter { $0.lowercased().contains(keyword.lowercased()) }
}
tableView.reloadData()
}
}
UISearchBar 代理(Swift)
extension ViewController: UISearchBarDelegate {
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchBar.setShowsCancelButton(true, animated: true)
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.text = ""
searchBar.resignFirstResponder()
searchBar.setShowsCancelButton(false, animated: true)
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
// 实时搜索
}
}
iOS 13+ 自定义 UISearchTextField(Swift)
if #available(iOS 13.0, *) {
let textField = searchBar.searchTextField
textField.font = .systemFont(ofSize: 16)
textField.backgroundColor = .systemGray6
textField.layer.cornerRadius = 10
textField.layer.masksToBounds = true
}
// 自定义取消按钮
searchBar.setValue("取消", forKey: "cancelButtonText")
九、总结
- UISearchBar:搜索输入控件,集成输入框、取消按钮、书签按钮、Scope Bar 分栏;常用属性 placeholder、tintColor、barStyle(UIBarStyle 类型,不是 UIBarMetrics)、showsCancelButton、showsScopeBar、scopeButtonTitles、inputAccessoryView;通常作为 tableView.tableHeaderView。
- UISearchBarDelegate:searchBarShouldBeginEditing(开始编辑)、searchBarCancelButtonClicked(取消)、searchBarSearchButtonClicked(搜索按钮)、searchBar:textDidChange:(实时搜索)、searchBar:selectedScopeButtonIndexDidChange:(分栏变化)。
- UISearchController(现代推荐,iOS 8+):封装 UISearchBar 和搜索状态管理,自动处理取消按钮、第一响应者、动画过渡;initWithSearchResultsController:nil 表示在当前控制器过滤,非 nil 表示用单独结果控制器;searchResultsUpdater 实时更新;obscuresBackgroundDuringPresentation 控制搜索时是否变暗背景;definesPresentationContext = YES 必须设置。
- 导航栏集成(iOS 11+):navigationItem.searchController 将搜索框集成到导航栏,配合 prefersLargeTitles 大标题,hidesSearchBarWhenScrolling 滚动时自动隐藏。
- 自定义 UISearchBar:iOS 13+ 用 searchBar.searchTextField 直接访问输入框自定义字体/颜色/圆角;取消按钮用 KVC
setValue:forKey:@"cancelButtonText"(不推荐遍历子视图,版本不稳定);搜索图标用 setImage:forSearchBarIcon:state:。 - 实时搜索过滤:用 NSPredicate
@"name CONTAINS[c] %@"模糊匹配(c 不区分大小写),或 Swift 用 filter + contains。 - 常见坑:barStyle 用 UIBarStyle 不是 UIBarMetrics;搜索框作为 tableHeaderView 不是 addSubview;UISearchController 必须设置 definesPresentationContext = YES;遍历子视图自定义在 iOS 13+ 可能失效。

浙公网安备 33010602011771号