// 这段代码可以实现导航栏时隐时现效果,kvo的应用
// ViewController.m
#import "ViewController.h"
#import "TableViewCell.h"
@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
{
UITableView * _tableView;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//self.view.backgroundColor = [UIColor blueColor];
self.navigationController.edgesForExtendedLayout = UIRectEdgeNone;
self.navigationController.navigationBar.translucent = YES;
[self.navigationController.navigationBar setBarTintColor:[UIColor orangeColor]];
_tableView = [[UITableView alloc]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 = [UIColor clearColor];
_tableView.bounces = YES;
[self.view addSubview:_tableView];
[_tableView addObserver: self forKeyPath: @"contentOffset" options: NSKeyValueObservingOptionNew context: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 = [[[NSBundle mainBundle]loadNibNamed:@"TableViewCell" owner:self options: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 {
[super didReceiveMemoryWarning];
// 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);
}