1

如何在UISearchDisplay控制器上使用文本字段而不是搜索栏?使用带有UISearchDisplayController的UITextField代替UISearchBar

我想通过摆脱放大镜图标和自定义背景来完全自定义搜索栏。同时停止调整大小并调出“取消”按钮。我看到有些人使用hacky的方式来编辑搜索栏api中不应该被编辑的部分。所以看起来在这个级别上定制的更可接受的方式是使用UITextfield而不是UISearchBar。但是网上似乎没有关于这样做的任何信息!

如果我使用文本字段,当文本更改以使UISearchDisplayController工作时,需要调用哪些方法?

回答

5

这里的技巧是重写UISearchDisplayController。它只有三件事。

  1. 将搜索栏移动到视图顶部并隐藏UINavigationBar。
  2. 在视图的其余部分放置一个透明的遮盖视图。
  3. 用任何搜索结果显示UITableView。

所以注册您的UIViewController作为的UITextField的委托,并开始..

-(void)textFieldDidBeginEditing:(UITextField *)textField { 
    //here is where you open the search. 
    //animate your textfield to y = 0. 
    //I usually make the search tableview and the cover a separate view, 
    //so I add them to my view here. 

    [self.navigationController setNavigationBarHidden:YES animated:YES]; 
} 

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { 
    NSString *searchText = [[NSString alloc] initWithString:[textField.text stringByReplacingCharactersInRange:range withString:string]]; 
    //display your search results in your table here. 
} 

-(void)textFieldDidEndEditing:(UITextField *)textField { 
    //hide all of your search stuff 
    [self.navigationController setNavigationBarHidden:NO animated:YES]; 
} 
相关问题