3

在我的拆分视图应用程序中,无法将搜索栏添加到拆分视图的 rootView

所以我在ui表视图的tableHeaderView中动态添加了搜索栏,如下所示

searchBar = [[UISearchBar alloc] init];
      searchBar.frame=CGRectMake(0, self.tableView.frame.origin.y, self.tableView.frame.size.width, 44);
      [searchBar sizeToFit];
      self.tableView.tableHeaderView = searchBar;

在此处输入图像描述

向下滚动时:iThe tableHeaderView 也会向下滚动,因此搜索栏也会滚动

在此处输入图像描述

滚动顶部时:tableHeaderView 也会滚动到顶部,因此搜索栏也会滚动

在此处输入图像描述

我实现了如下代码来解决此问题 this helps only when scrolls down,但是当我们将表格视图滚动到顶部时,它再次与表格视图一起移动

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
      CGRect rect = self.tableView.tableHeaderView.frame;
      rect.origin.y = MIN(0, self.tableView.contentOffset.y);
      self.tableView.tableHeaderView.frame = rect;
}

我需要始终将 tableHeaderView/ 搜索栏放在视图顶部

这个怎么做

4

3 回答 3

0

您可以添加 tabBar 与 tableView 分开

mySearchBar = [[UISearchBar alloc] init];
[mySearchBar setHidden:NO];
mySearchBar.placeholder = @"Search item here";
mySearchBar.tintColor = [UIColor darkGrayColor];
mySearchBar.frame = CGRectMake(0, 0, 320, 44);
mySearchBar.delegate = self;
[mySearchBar sizeToFit];
[mySearchBar setAutocapitalizationType:UITextAutocapitalizationTypeNone];

[self.view addSubview:mySearchBar];  

和tableView

UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 44, 320, 436)];
[self.view addSubview:tableView]; 

如果你想添加 xib 然后

在此处输入图像描述

于 2013-02-05T14:17:48.547 回答
0

将您的 searchBar 放在单独的视图中,并将该视图放在表格视图上方。这意味着它保持不变。

于 2013-02-05T13:49:40.700 回答
-2

我确信这已经被回答过,但假设你正在使用UITableViewController,你可以让view属性成为你想要的任何东西。因此,一种方法是设置一个容器视图,顶部是搜索栏,下面是表格,并view成为这个容器。默认情况下,tableView返回view,因此您需要注意的另一个细节是覆盖该tableView属性以返回实际的表视图(您已存储在 ivar 中)。代码可能如下所示:

@synthesize tableView = _tableView;

- (void)loadView
{
    [super loadView];

    _tableView = [super tableView];

    // Container for both the table view and search bar
    UIView *container = [[UIView alloc] initWithFrame:self.tableView.frame];

    // Search bar
    UIView *searchBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 50)];

    // Reposition the table view below the search bar
    CGRect tableViewFrame = container.bounds;
    tableViewFrame.size.height = tableViewFrame.size.height - searchBar.frame.size.height;
    tableViewFrame.origin.y = searchBar.frame.size.height + 1;
    self.tableView.frame = tableViewFrame;

    // Reorganize the view heirarchy
    [self.tableView.superview addSubview:container];
    [container addSubview:self.tableView];
    [container addSubview:searchBar];
    self.view = container;
}
于 2013-02-05T15:56:17.270 回答