第一步,创建一个通用格式和通用框架的搜索栏;
UISearchBar *mySearchBar = [[UISearchBar alloc] initWithFrame:CGRectZero];
[mySearchBar sizeToFit]; // if you give it CGRectZero and sizeToFit, it will shown exactly end of the your navigationBar.
mySearchBar.tintColor = [UIColor whiteColor];
mySearchBar.placeholder = @"Search Music";
mySearchBar.showsScopeBar = NO;
mySearchDisplayController *mySearchDisplay = [[mySearchDisplayController alloc] mySearchBar contentsController:self];
然后创建一个新的类类型“UISearchDisplayController”作为名称“mySearchDisplayController”,如您所见,我们应该将您的搜索栏合并到 3 行中。不要忘记为你的新类实现 UITableView 协议;
@interface mySearchDisplayController : UISearchDisplayController <UISearchDisplayDelegate, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource>
然后在您的新 mySearchDisplayController 类中实现该方法;
-(void)searchDisplayControllerWillBeginSearch:(mySearchDisplayController *)controller
{
self.searchResultsDataSource = self;
self.searchResultsTableView.delegate = self;
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1)
{
CGRect statusBarFrame = [[UIApplication sharedApplication] statusBarFrame];
[UIView animateWithDuration:0.01 animations:^{
for (UIView *subview in self.searchBar.subviews)
subview.transform = CGAffineTransformMakeTranslation(0, statusBarFrame.size.height);
}];
}
}
-(void)searchDisplayControllerWillEndSearch:(mySearchDisplayController *)controller
{
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1)
{
[UIView animateWithDuration:0.01 animations:^{
for (UIView *subview in self.searchBar.subviews)
subview.transform = CGAffineTransformIdentity;
}];
}
}
最后一步,您应该将搜索栏的新框架末端标识为您的表格视图;
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSInteger)scope
{
[self.filteredSearchResults removeAllObjects]; // First clear the filtered array.
for(NSDictionary *searchResult in // your search array)
{
NSString *searchableString = [NSString stringWithFormat:@"%@ %@", [searchResult objectForKey:@"//your search key"]];
NSRange stringRange = [searchableString rangeOfString:searchText options:NSCaseInsensitiveSearch];
}
}
[self.searchResultsTableView reloadData];
CGRect screenBound = [[UIScreen mainScreen] bounds];
CGSize screenSize = screenBound.size;
CGFloat screenHeight = screenSize.height;
CGRect frame = self.searchResultsTableView.frame;
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1)
{
frame.size.height = screenHeight-64.0f;
}
else
{
frame.size.height = screenHeight-44.0f;
}
self.searchResultsTableView.frame = frame;
}
我在 2 个月前为我的应用程序编写了该代码,它适用于 iOS 7 && 6 && 5。希望它有效。