searchDisplayControllerWillEndSearch在结束搜索时退出UIView

时间:2016-04-06 13:24:27

标签: ios objective-c uiview uisearchbar

我已经在UIView放置了UISearchBarUIButton以下是解释问题的屏幕截图: This is how it appears when I first run the app
^这是我第一次运行应用时的显示方式 This is how it gets when I want to enter the text
^这就是我想输入文字的方式 Finally this is the size it gets after I end the search ^ ^最后这是我结束搜索后得到的尺寸
这里最重要的一点是我没有使用UINavigationBar红色是UIView。我没有为它的用户界面编码任何内容,我只是将其放在.xib中并通过autoResizing进行设置。我只是为UISearchBar撰写的[_searchBarTop setBackgroundImage:[UIImage new]];只是为了让背景图片消失。
我已经尝试了 self.searchBarTop.clipsToBounds = YES;和此

- (void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller
    {
        self.searchDisplayController.searchBar.translatesAutoresizingMaskIntoConstraints = YES;
        [self.searchDisplayController setActive:NO animated:YES];
    }

我使用searchdisplaycontroller并希望使用 但它仍然是一样的。有什么建议吗?

2 个答案:

答案 0 :(得分:1)

UISearchDisplayController在iOS 8.0中首次被弃用,实际上是UISearchDisplayDelegate。你应该使用UISearchController它的委托,UISearchControllerDelegate和它的searchBar属性。

编辑 - 添加示例

 // your class needs to conform to the following protocols 

 <UISearchResultsUpdating, UISearchControllerDelegate>
 // define property for your search controller
 @property (nonatomic) UISearchController *mySearchController;

 // instantiate the search controller - in viewDidLoad should work
 // if you want to handle results manually the searchResultsController can be nil, or you can set it to

 self.mySearchController = [[UISearchController alloc]initWithSearchResultsController:nil];
 [self.mySearchController.searchBar sizeToFit];
 self.mySearchController.searchResultsUpdater = self;
 self.mySearchController.delegate = self;
 self.mySearchController.dimsBackgroundDuringPresentation = NO;

 // add the searcher to a properly constrained "Container" or "wrapper" UIView 
 [self.containerView addSubView:self.mySearchController.searchBar];
 [self.mySearchController.searchBar sizeToFit]; 
 self.definesPresentationContext = YES;

然后,您可以通过实施UISearchResultsUpdating协议所需的方法来响应搜索栏中的输入:

 - (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
      NSString *text = searchController.searchBar.text;
      /// do whatever you need to with the text typed in to the search bar
 }

最后,请务必阅读Apple's documentation

答案 1 :(得分:1)

如果您在UISearchBar中使用简单的UIView,则无需每sè使用UISearchController。您可以简单地使用UISearchBar,而不是相应的代表。

至于调整大小的问题,我认为你有灵活宽度的自动调整,而你需要静态宽度,静态边。将此应用于您的UIView和嵌入式UISearchBar。那应该可以解决你的问题。如果问题仍然存在,请告诉我。

如果自动调整不起作用,你可以像这样强制它:

-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    CGRect frame = self.searchBarTop.frame;
    frame.origin.x = 33;
    frame.size.width = self.view.frame.size.width - 41;

    [UIView animateWithDuration:0.5 animations:^{
        self.searchBarTop.frame = frame;
    }];
});
}