我有两个问题:
- 我的iPhone屏幕上有一个搜索栏。当我滚动屏幕时,我的搜索栏也会滚动。我想解决这个问题或让它变得绝对。
- 搜索不起作用,如果我输入 A,那么我应该得到所有以字母 A 开头的单词。
我正在尝试的代码:
- (void)viewDidLoad {
[super viewDidLoad];
const NSInteger searchBarHeight = 45;
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0,
self.tableView.frame.size.width, searchBarHeight)];
searchBar.delegate = self;
self.tableView.tableHeaderView = searchBar;
[searchBar release];
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithTitle:@"Refresh"
style:UIBarButtonItemStyleBordered target:self action:@selector(onAddContact:)];
self.navigationItem.rightBarButtonItem = addButton;
UILabel *label = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont boldSystemFontOfSize:20.0];
label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
label.textAlignment = UITextAlignmentCenter;
label.textColor = [UIColor whiteColor]; // change this color
self.navigationItem.titleView = label;
label.text = NSLocalizedString(@"All Contacts", @"");
[label sizeToFit];
content = [DataGenerator wordsFromLetters];
indices = [[content valueForKey:@"headerTitle"] retain];
}
您需要将搜索栏与表视图分开。只需将搜索栏添加到视图中,而不是将其添加到表中。代码如下:
[self.view addSubview:searchBar];
然后添加表视图。
对于UISearchDisplayController示例,请按照本教程进行操作:http://cocoabob.net/?p=67或http://blog.mugunthkumar.com/coding/iphone-tutorial-uisearchdisplaycontroller-with-nspredicate/
源代码也可用。如果您不明白,请告诉我。我有一个项目,所有这些都已经实施。
当您滚动时,此时的UITableView
也UISearchBar
滚动,因为您将UISearchBar
添加为标题视图UITableView
看到此行。
self.tableView.tableHeaderView = searchBar;
所以它的滚动带有UITableView
,这里为了修复UISearchBar
只是添加为带有框架的self.view
的子视图,但在UITableView
外部 例如..
[yourSearchBar setFrame:CGRectMake(0, 0, 320, 44)];
[self.view addSubview:yourSearchBar];
有关更多信息,请参阅下面带有教程的链接和演示,了解UISearchBar
UITableView
- filtering-a-uitableview-with-a-uisearchbar-using-core-data
- 连接-uitableview-with-uisearchbar//了解如何使用
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
方法使用搜索栏文本字段更改本教程中的数组