在iOS的工具栏中包含UISearchBar

我正在尝试在工具栏上放置一个.xib文件的UISearchBar。 我可以将search栏拖放到工具栏上,但显示以下错误。

ControllerName.xib:error: illegal Configuration: UISearchBar embedded in UIBarButtonItems (Only available ub iPad documents).

请指导我如何将UISearchBar包含到xib中的工具栏中。

据我所知,除非你使用IPAD进行开发,否则不能直接在UIToolBar中添加UISearchBarIPHONE中 ,你需要首先将UISearchBar添加到customView,然后以编程方式将其添加到工具栏

 // your searchbar UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(xposition, yposition, width, height)]; //create a customview and make its frame equal to your searchbar UIView *searchBarView = [[UIView alloc] initWithFrame:searchBar.frame]; // add your searchbar to the custom view [searchBarView addSubview:searchBar]; //finally add it to your bar item of the toolbar UIBarButtonItem *searchBarItem = [[UIBarButtonItem alloc] initWithCustomView:searchBarView]; 

通过编程:

 UIToolbar *Toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)]; [Toolbar sizeToFit]; UISearchBar *testbar = [[UISearchBar alloc] initWithFrame:CGRectMake(0,2,250,38)]; NSMutableArray *barItems = [[NSMutableArray alloc] init]; UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil]; [barItems addObject:flexSpace]; UIBarButtonItem *btnCancel = [[UIBarButtonItem alloc] initWithTitle:@"Button" style:UIBarButtonItemStyleBordered target:self action:@selector(ButtonMethod)]; [barItems addObject:btnCancel]; [Toolbar setItems:barItems animated:YES]; [Toolbar addSubview:testbar]; [self.view addSubview:Toolbar]; 

这里是button方法;

 -(void)ButtonMethod { // Write Code for ButtonMethod Method } 

现在你可以使用Interface Builder来修复Xcode 8.2中的这个问题。 我认为他们之前禁用了它,因为在iOS 8.0之前iOS上不允许popup窗口,而工具栏中的search栏意味着最多使用popup窗口。 但是他们忘了在iOS 8.0中禁用它。