iOS Swift&OC 模仿主流App 实现滑动视图隐藏导航栏

简单直接上图上代码 -.- 一个GIF图5M?

@property (nonatomic, strong) UITableView *tableViewScroll;
@property (nonatomic, assign) double recordDistance; //记录滑动的距离
@property (nonatomic, strong) UIView *customView;
@property (nonatomic, strong) UIButton *btn;

创建所需要的视图

- (UITableView *)tableViewScroll
{
    if (_tableViewScroll == nil) {
        _tableViewScroll = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight) style:UITableViewStylePlain];
        _tableViewScroll.delegate = self;
        _tableViewScroll.dataSource = self;
        [_tableViewScroll registerClass:[UITableViewCell class] forCellReuseIdentifier:cellIdentifier];
    }
    return _tableViewScroll;
}
- (UIView *)customView
{
    if (_customView == nil) {
        _customView = [[UIView alloc] initWithFrame:CGRectMake(0, 44, screenWidth, 30)];
        _customView.backgroundColor = [UIColor lightGrayColor];
    }
    return _customView;
}
- (UIButton *)btn
{
    if (_btn == nil) {
        _btn = [UIButton buttonWithType:UIButtonTypeCustom];
        _btn.frame = CGRectMake(screenWidth - 70, 5, 40, 20);
        [_btn setTitle:@"关注" forState:UIControlStateNormal];
        _btn.titleLabel.font = [UIFont systemFontOfSize:13];
        _btn.backgroundColor = [UIColor greenColor];
    }
    return _btn;
}

关键在于scrollView协议方法中的处理

// Objective-C
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // 记录滑动距离
    self.recordDistance = scrollView.contentOffset.y;
    NSLog(@"histroy_y ======== %lf", self.recordDistance);
}
// Swift
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        self.recordDistance = scrollView.contentOffset.y
    }
// Objective-C
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSLog(@"y ======= %lf", scrollView.contentOffset.y);
    scrollView.contentOffset.y > self.recordDistance ? scrollView.contentOffset.y < self.recordDistance ? [self.navigationController setNavigationBarHidden:NO animated:YES]:[self.navigationController setNavigationBarHidden:YES animated:YES] : [self.navigationController setNavigationBarHidden:NO animated:YES];
}
// Swift
func scrollViewDidScroll(scrollView: UIScrollView) {
        scrollView.contentOffset.y > self.recordDistance ? scrollView.contentOffset.y < self.recordDistance ? self.navigationController?.setNavigationBarHidden(false, animated: true):self.navigationController?.setNavigationBarHidden(true, animated: true) : self.navigationController?.setNavigationBarHidden(false, animated: true);
    }

省略了tableview相关的代码
在viewDidload中

    [self.view addSubview:self.tableViewScroll];
    [self.navigationController.navigationBar addSubview:self.customView];
    [self.customView addSubview:self.btn];
    self.title = @"这是一个测试页";
    self.navigationController.navigationBar.barTintColor = [UIColor lightGrayColor];

觉得还可以请点个赞, 我要申请微博加V. 点个赞吧客官 -.- 哈哈哈

你可能感兴趣的:(swift)