TableView & CelliOS动画技巧iOS Developer

iOS 滑动TableView控制导航栏隐藏与显示

2016-07-07  本文已影响3391人  Me小酥酥

分享一个小Demo,滑动TableView的时候控制导航栏的隐藏与显示,实际并不难,也没什么技巧,在这里记录下,希望大家能给些改进建议。


2016-07-07 17_49_20.gif
那么我们开始看代码吧,直接用的UITableViewController
 @interface TableViewController ()
{
    NSMutableArray * dataSource;    //数据源
    CGFloat beginContentY;          //开始滑动的位置
    CGFloat endContentY;            //结束滑动的位置
    CGFloat sectionHeaderHeight;    //section的header高度
}
@end

@implementation TableViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    sectionHeaderHeight = 40;

    dataSource = [[NSMutableArray alloc] init];
    for(int i=0;i<100;i++)
    {
        NSString * name = [NSString stringWithFormat:@"%d",i];
        [dataSource addObject:name];
    }
    [self.navigationController.navigationBar setBarTintColor:[UIColor redColor]];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dataSource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return sectionHeaderHeight;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return @"this is a demo";
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

    NSString * str = [dataSource objectAtIndex:indexPath.row];
    cell.textLabel.text = str;

    return cell;
}

// 当开始滚动视图时,执行该方法。一次有效滑动(开始滑动,滑动一小段距离,只要手指不松开,只算一次滑动),只执行一次。
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    //获取开始位置
    beginContentY = scrollView.contentOffset.y;
}

// 滑动scrollView,并且手指离开时执行。一次有效滑动,只执行一次。
// 当pagingEnabled属性为YES时,不调用,该方法
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    //获取结束位置
    endContentY = scrollView.contentOffset.y;
    if(endContentY-beginContentY > 100)
    {
        [UIView animateWithDuration:0.25 animations:^{
            CGRect rect = self.navigationController.navigationBar.frame;
            rect.origin.y = -44;
            self.navigationController.navigationBar.frame = rect;
        }];
        sectionHeaderHeight = 0;
        [self.tableView reloadData];
    } else if(endContentY-beginContentY < -100)  {
        [UIView animateWithDuration:0.25 animations:^{
            CGRect rect = self.navigationController.navigationBar.frame;
            rect.origin.y = 20;
            self.navigationController.navigationBar.frame = rect;
        } completion:^(BOOL finished) {
            sectionHeaderHeight = 40;
            [self.tableView reloadData];
        }];
    }
}

很简单的,一点都不复杂。文中的备注也很少,相信可以看得明白,希望大家多提意见。

上一篇 下一篇

猜你喜欢

热点阅读