iOS ReviewiOS实战

(KVO||Delegate)滚动视图上滑动改变导航条颜色或者透

2016-06-29  本文已影响397人  952625a28d0d
#import "ViewController.h"

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    // 添加监听者
    [self.tableView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    // 去掉多余的边界
    self.edgesForExtendedLayout = UIRectEdgeNone;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.textLabel.text = @"Jafar";
    }
    return cell;
}

#pragma mark - 属性值发生改变的时候回调
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    
    // 获取偏移量
    CGFloat offset = self.tableView.contentOffset.y;
    CGFloat delta = -offset / 64.f + 1.f;
    
    // 如果大于0则取
    delta = MAX(0, delta);
    
    // 创建导航栏颜色
    UIColor *color = [UIColor redColor];
    
    if (offset<0) {
        self.navigationController.navigationBar.backgroundColor = [color colorWithAlphaComponent:0];
    }else {
        // 如果delta小于1 则取 并赋值给导航栏颜色的透明度
        self.navigationController.navigationBar.backgroundColor=[color colorWithAlphaComponent:MIN(1, delta)];
    }
    
    NSLog(@"navigationBar's alpha is %f",self.navigationController.navigationBar.alpha);
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSLog(@"offset---scroll:%f",self.tableView.contentOffset.y);
    UIColor *color=[UIColor redColor];
    CGFloat offset=scrollView.contentOffset.y;
    if (offset<0) {
        self.navigationController.navigationBar.backgroundColor = [color colorWithAlphaComponent:0];
    }else {
        CGFloat alpha=1-((64-offset)/64);
        self.navigationController.navigationBar.backgroundColor=[color colorWithAlphaComponent:alpha];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end```

![ScrollView+NavAlpha.gif](http:https://img.haomeiwen.com/i189984/773918ba41a97966.gif?imageMogr2/auto-orient/strip)
上一篇 下一篇

猜你喜欢

热点阅读