实现ios手机QQ空间导航栏控制器时隐时现效果,kvo的应用

来源:互联网 发布:会员积分软件dnnyun 编辑:程序博客网 时间:2024/05/22 11:44

//  这段代码可以实现导航栏时隐时现效果,kvo的应用

//  ViewController.m


#import "ViewController.h"

#import "TableViewCell.h"

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>

{

   UITableView * _tableView;


}

@end


@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    //self.view.backgroundColor = [UIColor blueColor];

    self.navigationController.edgesForExtendedLayout =UIRectEdgeNone;

    self.navigationController.navigationBar.translucent = YES;

    [self.navigationController.navigationBarsetBarTintColor:[UIColororangeColor]];

    _tableView = [[UITableViewalloc]initWithFrame:CGRectMake(0,0, self.view.frame.size.width,self.view.frame.size.height-64)style:UITableViewStylePlain];

    _tableView.delegate =self;

    _tableView.dataSource =self;

    _tableView.backgroundColor = [UIColorclearColor];

    _tableView.bounces =YES;

    [self.viewaddSubview:_tableView];

    

    [_tableViewaddObserver: selfforKeyPath: @"contentOffset"options: NSKeyValueObservingOptionNewcontext:nil];

}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{

    CGFloat offset=_tableView.contentOffset.y;

    NSLog(@"offset:%f",offset);//越来越大 想要实现效果:一开始全显示,后来颜色变浅

   CGFloat delta=1-offset/100.f;

    delta=MIN(1,delta);

   NSLog(@"%f",delta);

    self.navigationController.navigationBar.alpha=MIN(1,delta);


}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

   return 1;

}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

   return 100;

}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{


    TableViewCell * cell = [[[NSBundlemainBundle]loadNibNamed:@"TableViewCell"owner:selfoptions:nil]firstObject];

   if (indexPath.row==0) {

        cell.myImage.hidden =NO;

    }else{

        cell.myImage.hidden =YES;

    

    }

    

   return cell;


}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{


   if (indexPath.row==0) {

       return 180.0f;

    }

   return 60.0f;

}


- (void)didReceiveMemoryWarning {

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end






另附一则参考别人相反的实现

//添加监听者

[self.tableView addObserver: self forKeyPath: @"contentOffset" options: NSKeyValueObservingOptionNew context: nil];

/**

 *  监听属性值发生改变时回调

 */

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context

{

    CGFloat offset = self.tableView.contentOffset.y;

    CGFloat delta = offset / 64.f + 1.f;

    delta = MAX(0, delta);

    [self alphaNavController].barAlpha = MIN(1, delta);

}




0 0