iOS Developer

固定searchBar于tableView上方(非headVie

2016-12-06  本文已影响435人  木子F

直接上码

    #import "SearchViewController.h"

    // 这里要添加代理...
    @interface SearchViewController ()<UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, UISearchDisplayDelegate>
    @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

后记

上一篇 下一篇

猜你喜欢

热点阅读