上次写了一个关于左右滚动使用scroll实现的轮播,今天闲着没事也搞了一个上下滚动的字体轮播,大致思路是一样的。
如果想实现上下滚动的轮播,首先要确定几点
1.scroll可见范围(可滚动范围)
2.contentSize(最大滚动范围)
3.当然还有数据源,和左右滚动类似,item+2
好了,确定了这几点有了思路就可以直接来代码了
声明属性
@property (strong, nonatomic) UIScrollView * verticalScroll;//承载数据的父视图
@property (strong, nonatomic) NSArray * titleArrays;//数据源
@property (strong, nonatomic) NSTimer * myTimer;//定时器管控轮播
数据源(这里对数据做了处理,数量+2)
-(NSArray *)titleArrays{
if (!_titleArrays) {
_titleArrays = [NSArray arrayWithObjects:@"今天是一个好天气",@"温度达到了30度以上",@"可是我并没有感觉很热",@"因为什么呢",@"公司开空调了",@"这个是不是可以有啊",@"今天是一个好天气",@"温度达到了30度以上", nil];
}
return _titleArrays;
}
父视图包括数据的创建
-(UIScrollView *)verticalScroll{
if (!_verticalScroll) {
_verticalScroll = [[UIScrollView alloc]init];
_verticalScroll.center = CGPointMake(SCREEN_WIDTH/2, SCREEN_HEIGHT/2);
_verticalScroll.bounds = CGRectMake(0, 0, 130, 60);
//_verticalScroll.pagingEnabled = YES;
_verticalScroll.showsVerticalScrollIndicator = NO;
_verticalScroll.scrollEnabled = NO;
_verticalScroll.bounces = NO;
_verticalScroll.delegate = self;
[self.view addSubview:_verticalScroll];
CGFloat scaleH = 20;
CGFloat Height = 20;
CGFloat H = 0;
for (int i =0; i<self.titleArrays.count; i++) {
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(10, H+scaleH, CGRectGetWidth(_verticalScroll.frame)-20, Height);
[button setTitle:self.titleArrays[i] forState:UIControlStateNormal];
[button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
button.tag = i+10;
[_verticalScroll addSubview:button];
H = button.frame.origin.y+button.frame.size.height+scaleH;
}
_verticalScroll.contentSize = CGSizeMake(0, H);
}
return _verticalScroll;
}
还差一个管控无限轮播的定时器(我是在进入界面的时候就创建的,可根据项目需求来)
-(void)viewWillAppear:(BOOL)animated{
self.verticalScroll.backgroundColor = [UIColor whiteColor];
_myTimer = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(changeScrollContentOffSetY) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:_myTimer forMode:NSRunLoopCommonModes];
}
实现定时器方法
-(void)changeScrollContentOffSetY{
//启动定时器
CGPoint point = self.verticalScroll.contentOffset;
[self.verticalScroll setContentOffset:CGPointMake(0, point.y+CGRectGetHeight(self.verticalScroll.frame)) animated:YES];
}
当然了,滚动代理也是要有的。因为这里没有考虑手动滑动可以滚动的情况,所以只写一个代理协议即可,代码如下
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
NSLog(@"endani");
if (scrollView.contentOffset.y==scrollView.contentSize.height-CGRectGetHeight(self.verticalScroll.frame)){
[scrollView setContentOffset:CGPointMake(0, CGRectGetHeight(self.verticalScroll.frame))];
}
}
最后定时器记得在退出本界面的时候记得销毁
-(void)viewWillDisappear:(BOOL)animated{
[_myTimer invalidate];
_myTimer = nil;
}