谈一谈UIScrollView的scrollsToTop属性

相信很多人都没有注意到iOS有这样一个隐藏的功能:当前页面有滚动视图( UIScrollView 或者 UIScrollView 的子类,下面我都称作滚动视图),触摸状态栏,视图会自动滚动的最顶端,相当于一些网页的回到顶端的功能。下面给个图来展示下:


图1:触摸状态栏回到顶部

一. 遇到的问题

如果页面有多个滚动视图,如顶部一个广告轮播控件(假如是基于 UIScrollView 的轮播控件),下面是一个TableView,你会发现触摸状态栏没有反应了,回到顶部功能失效。

二. 解决问题

细细研究了一番返现,UIScrollView 有个scrollsToTop属性,这个属性就是控制滚动到顶部手势的开关。它的默认值是 YES ,所以不用我们设置,默认是支持滚动到顶部的。具体详细描述如下:

The scroll-to-top gesture is a tap on the status bar. When a user makes this gesture, the system asks the scroll view closest to the status bar to scroll to the top. If that scroll view has scrollsToTop
set to NO , its delegate returns NO from scrollViewShouldScrollToTop:
, or the content is already at the top, nothing happens.

简单点的说就是有两种方式来设定 scroll to top,一个是设置 scrollsToTop 属性,另一个是实现UIScrollView的代理方法scrollViewShouldScrollToTop:。如果滚动视图scrollsToTop属性设为 NO ,它的代理方法scrollViewShouldScrollToTop:返回NO,或者内容已经在顶部了,这样触摸状态栏,是没有任何反应的。

好了,继续回到上面遇到的问题,既然默认是YES,为什么回到顶部的功能失效了呢,其实仔细想一想就知道了,因为有两个 scrollView,他们默认都有 scroll to top 功能,所以触摸状态栏时,系统无法判断是使哪个ScrollView回到顶部。

解决方案很简单,就是设置其中一个ScrollView的 scrollsToTop 值为 NO(例如我将广告轮播控件的 scrollsToTop 设为 NO ),这样系统就知道要使哪个 ScrollView 回到顶部了。如果当前页面有多个滚动视图的话,要确保只有一个滚动视图scrollsToTop的值为YES

use it like [[ScrollviewModel sharedInstance] initWithChannels:@[@{@"channelID" : @"channelId_toutiao", @"channelName": @"头条", @"type" : @"normal"}, @{@"channelID" : @"channelId_local", @"channelName": @"北京", @"type" : @"web"}, @{@"channelID" : @"channelId_yule", @"channelName": @"娱乐", @"type" : @"normal"}, @{@"channelID" : @"channelId_junshi", @"channelName": @"军事", @"type" : @"normal"}, @{@"channelID" : @"channelId_video", @"channelName": @"视频", @"type" : @"normal"}, @{@"channelID" : @"channelId_meinv", @"channelName": @"美女", @"type" : @"normal"}, @{@"channelID" : @"channelId_duanzi", @"channelName": @"段子", @"type" : @"web"}, @{@"channelID" : @"channelId_keji", @"channelName": @"科技", @"type" : @"normal"}, @{@"channelID" : @"channelId_fang", @"channelName": @"房产", @"type" : @"normal"}, @{@"channelID" : @"channelId_zhibo", @"channelName": @"直播", @"type" : @"normal"}, ]]; self.topScrollview = [TopScrollview.alloc initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, 41)]; _topScrollview.contentInset = UIEdgeInsetsMake(0, 0, 0, IFScreenFit2s(45.f)); _topScrollview.scrollsToTop = NO; [self.view addSubview:_topScrollview]; _topScrollview.model = [ScrollviewModel sharedInstance]; self.controllerScrollview = [ControllerScrollView.alloc initWithFrame:CGRectMake(0, self.topScrollview.frame.origin.y self.topScrollview.frame.size.height, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)]; [self.view addSubview:_controllerScrollview]; self.controllerScrollview.model = [ScrollviewModel sharedInstance];
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值