码迷,mamicode.com
首页 > 其他好文 > 详细

UITableView中headerView视察滚动的简单实现

时间:2014-06-24 13:35:15      阅读:297      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   ext   color   

简单思路:实例一个UIScrollView,在scrollView上添加两个UIView, 为scrollView添加观察者,观察scrollView的contentOffset属性.

当偏移量改变时,改变UIView视图的坐标.

示例代码:

@interface RootViewController ()

@property (nonatomic, copy) UIScrollView *scrollView;
@property (nonatomic, copy) UIView *headView;
@property (nonatomic, copy) UIView *headView2;

@end

@implementation RootViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 创建一个UIScrollView
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(10, 20, 300, 440)];
    [self.view addSubview:_scrollView];
    _scrollView.backgroundColor = [UIColor orangeColor];
    _scrollView.contentSize = CGSizeMake(0, 2000);
    _scrollView.delegate = self;
    // 创建两个UIView并添加到scrollView上
    _headView = [[UIView alloc] initWithFrame:CGRectMake(0, 200, 300, 50)];
    [_scrollView addSubview:_headView];
    _headView.backgroundColor = [UIColor grayColor];
    
    _headView2 = [[UIView alloc] initWithFrame:CGRectMake(0, 800, 300, 40)];
    [_scrollView addSubview:_headView2];
    _headView2.backgroundColor = [UIColor colorWithRed:0.255 green:0.718 blue:1.000 alpha:1.000];
    //为scrollView添加观察者
    [_scrollView addObserver:self forKeyPath:@"contentOffset" options:(NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew) context:@"headView"];
    
}

// 被观察者的属性发生变化就调用此方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (context == @"headView") {
        if ((_scrollView.contentOffset.y > 200 && _scrollView.contentOffset.y <= 760)) {
            _headView.frame = CGRectMake(0, _scrollView.contentOffset.y, 300, 50);
        }
        if (_scrollView.contentOffset.y >= 760 && _scrollView.contentOffset.y <= 800.0) {
            float y = 760;            
            _headView.frame = CGRectMake(0, y, 300, 50);
        }
        if (_scrollView.contentOffset.y >= 800) {
            _headView2.frame = CGRectMake(0, _scrollView.contentOffset.y, 300, 40);
        }
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}
@end 

基本实现了效果,如果有什么错误或者更好的想法,欢迎指正.

UITableView中headerView视察滚动的简单实现,布布扣,bubuko.com

UITableView中headerView视察滚动的简单实现

标签:style   class   blog   code   ext   color   

原文地址:http://www.cnblogs.com/NatureZhang/p/3805061.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!