固定searchBar于tableView上方(非headView)

直接上码

    #import "SearchViewController.h"

    // 这里要添加代理...
    @interface SearchViewController ()
    @property (strong, nonatomic) UISearchDisplayController *searchDisplayC;

    @end

    @implementation SearchViewController

    - (void)viewDidLoad {
        [super viewDidLoad];
        
        UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
        tableView.delegate = self;
        tableView.dataSource = self;
        // 这里需要设置偏移量
        tableView.contentInset = UIEdgeInsetsMake(44, 0, 0, 0);
        tableView.contentOffset = CGPointMake(0, - 44);
        // 添加tableView
        [self.view addSubview:tableView];
    
        // 需要设置searchBar的位置
        UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 64, 375, 44)];
        self.searchDisplayC = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
        self.searchDisplayC.searchBar.delegate = self;
        self.searchDisplayC.delegate = self;
        // 添加searchBar
        [self.view addSubview:self.searchDisplayC.searchBar];
    
    
    }

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
        return 30;
    }

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        cell.backgroundColor = [UIColor cyanColor];
        return cell;
    }

    ----主要看下面两个代理方法----
    // 开始搜索时向上移动searchBar
    - (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller{
        [UIView animateWithDuration:0.25 animations:^{
            controller.searchBar.frame = CGRectMake(0.f, 20.f, 375, 44);
        }];
    }
    // 结束搜索时向下移动searchBar
    - (void)searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller{
        [UIView animateWithDuration:0.25 animations:^{
            controller.searchBar.frame = CGRectMake(0.f, 64.f, 375, 44);
        }];
    }

    @end

后记

  • UISearchDisplayController 8.0后不推荐使用了, 现在是推荐使用UISearchController. 而使用UISearchController时, 用类似的方法发现改不了收回时的位置,searchBar会一直置顶 ( 被navigationBar挡住 - 有的话 ). 若有读者解决了, 请留个解决方法, 谢谢了.

你可能感兴趣的:(固定searchBar于tableView上方(非headView))