使用tableHeaderView中的UIView创建UISearchBar行为

时间:2012-01-11 17:37:01

标签: ios uitableview uiview header uisearchbar

如果我有一个UISearchBar到tableHeaderView,当我向下滚动表格视图时,搜索栏会自动隐藏。我想要相同的行为,而是将一个UISearchBar添加到tableHeaderView我想添加一个UIView。

这是一个问题视频:

http://www.youtube.com/watch?v=NPTRaT2A5vU

5 个答案:

答案 0 :(得分:1)

在ViewController(不是TableViewController)中使用TableView,然后只将SearchBar添加到该视图的顶部(将tableview调整为适应大小)。我在几乎所有需要使用SearchBar过滤的VC中都这样做。这使搜索栏始终可见并且运行良好。

如果需要,我可以发送一个完整的例子

答案 1 :(得分:1)

我还没有看到一个解决方案正确模仿从UINeigationBar中分配给UITableView.tableHeaderView的UISearchBar获得的自动(未记录的,据我所见)滚动行为。除了您的视频,这种行为也可以在Apple的iOS应用程序中看到,例如邮件和音乐。

我发现实现此目的的一种方法是将一个UISearchBar分配给tableHeaderView,然后在UISearchBar(这是一个UIView子类)的顶部添加自定义视图。您仍然可以使用特殊的表格滚动行为来隐藏&显示表头,但改为使用您自己的视图。这假设您可以使视图与UISearchBar的大小相同。

例如,在viewDidLoad中:

self.tableView.tableHeaderView = [[[UISearchBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 44.0f)] autorelease];
[self.tableView.tableHeaderView addSubview:myView];

不可否认,有点黑客,但这种策略确实有效。

答案 2 :(得分:0)

从字面上看,该视频所做的是它不添加tableHeaderView,它使用单元格.contentView属性将自定义视图放在第一个单元格中,然后开始添加测试单元格。所以你接受indexPath的cellViewForIndexPath方法并检查它是否为0然后添加你的自定义视图。然后添加细胞。所有视频都将单元格向下移动一个,并使用代码

将一个视图添加到cell0
[cell.contentView addSubview:CustomView];

这就是你需要在那里放置自定义视图。

答案 3 :(得分:0)

如果有人读到这个,就像我一样,我找到了解决这个问题的方法。这很简单

myTableView.contentOffset = CGPointMake(0, heightOfView);

因此,您必须知道视图的高度,此解决方案还有另一个缺点。如果表格视图中没有足够的内容可滚动,并且向下滚动视图将被显示,您无法再隐藏它。就我而言,现在这是可以接受的。

如果有人使用UIVearchBar功能使用UIView。请发帖:)

希望这有助于某人

答案 4 :(得分:0)

重申Daan Vermeulen的答案,只需通过搜索栏的高度来偏移滚动视图就可以了。由于我在表格的标题视图中添加了搜索栏,因此我将向上移动标题视图高度的高度。我的目标是iOS8,这是针对viewdidload方法的;所以代码位如下:

//initiate the search controller
//use the original tableview controller itself to manage search
//don't dim the underlying content to show the filtered results as the user types into the search bar.
//search scope bar is not used. assign an empty array to the scopebuttontitles property (this is required with iOS8)
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.searchController.dimsBackgroundDuringPresentation = NO;
self.searchController.searchBar.scopeButtonTitles = [[NSArray alloc] init];

//use the original tableview controller as a delegate and implement the UISearchResultsUpdating protocol
//add the search bar view to the table view header
//search view covers the table view when active. make the table view controller define the presentation context
//to ensure that search bar fits the screen. (this is required with iOS8)
self.searchController.searchBar.delegate = self;
self.tableView.tableHeaderView = self.searchController.searchBar;
self.definesPresentationContext = YES;
[self.searchController.searchBar sizeToFit];

//offset scrollview content by tableheaderview height
self.tableView.contentOffset = CGPointMake(0, self.tableView.tableHeaderView.bounds.size.height);