UIScrollView的子页面悬停效果

今天想要在UIScrollView上做一个简单的悬停效果,感觉挺简单的一个功能,也没太放在心上,很快写好了,一测试发现达不到效果。于是就在网上大概搜了一下,有使用约束做的,我觉得太麻烦。然后就只剩下一种方法了。这种实现的方法核心就是,判断scrollViewcontentOffsetY,当需要悬停的时候,将这个view添加到self.view上,如果不需要悬停的时候,再把这个view添加到scrollView上。这么简单的功能,怎么能做得这么复杂呢。于是晚上到家仔细想了一下,就是一个简单的数学计算。
因为代码实在是太简单了,也不发demo了,直接贴代码

#define screenBounds [UIScreen mainScreen].bounds

@interface ViewController ()
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *searchView;
@property (nonatomic, strong) UIView *selectView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) CGFloat minY;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    _scrollView = [[UIScrollView alloc]initWithFrame:screenBounds];
    _scrollView.backgroundColor= [UIColor purpleColor];
    _scrollView.scrollEnabled = YES;
    _scrollView.delegate = self;
    _scrollView.scrollsToTop = YES;
    _scrollView.alwaysBounceVertical = YES;
    _scrollView.showsVerticalScrollIndicator = YES;
    [self.view addSubview:_scrollView];
    
    _searchView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(screenBounds), 80)];
    _searchView.backgroundColor = [UIColor orangeColor];
    [self.scrollView addSubview:_searchView];
    
    _selectView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_searchView.frame), CGRectGetWidth(screenBounds), 50)];
    _selectView.backgroundColor = [UIColor greenColor];
    [self.scrollView addSubview:_selectView];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_selectView.frame), CGRectGetWidth(screenBounds), 500)];
    [self.scrollView addSubview:label];
    label.numberOfLines = 0;
    label.text = @"龙丰街道卢卡就离开份简历卡仕达解放路;安静的服控件埃里克森;附近的看;拉萨江龙丰街道卢卡就离开份简历卡仕达解放江龙丰街道卢卡就离开份简历卡仕达解放路;";
    
    _minY = CGRectGetMinY(_selectView.frame);
}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat offsetY = scrollView.contentOffset.y;
    
    CGRect frame = _selectView.frame;
    if (offsetY >= _minY) {
        frame.origin.y = offsetY;
    }else{
        frame.origin.y = _minY;
    }
    _selectView.frame = frame;
    NSLog(@"offsetY=%lf",offsetY);
}

你可能感兴趣的:(UIScrollView的子页面悬停效果)