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

简单思路:实例一个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 

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

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