今天分享一个老虎机滚动效果的号码球滚动视图
Github地址:BTScrollBallView
看看效果
![](https://img.haomeiwen.com/i2334426/aeef658a72b182fe.gif)
- 可以自定义号码球样式;
- 通过代理方式设置数据和号码球样式,使感受和CollectionView相似;
- 每一个滚动列作为一组号码球,每个球都可单独控制;
- 使用CALayer作为图层,低内存;
cocoapod集成
pod BTScrollBallView
使用方法
1、初始化视图
- (BTScrollBallView *)scrollBall{
if (!_scrollBall) {
_scrollBall = [[BTScrollBallView alloc]init];
_scrollBall.backgroundColor = UIColor.clearColor;
_scrollBall.dataSource = self;
_scrollBall.delegate = self;
_scrollBall.backgroundColor = UIColor.blueColor;
}
return _scrollBall;;
}
2、设置好数据源方法
// MARK: - MKScrollBallDataDelegate
// 设置号码球大小
- (CGSize)scrollBall:(BTScrollBallView *)scrollBall sizeForItemAtIndex:(NSInteger)section{
return CGSizeMake(CGRectGetHeight(scrollBall.bounds), CGRectGetHeight(scrollBall.bounds));
}
// 设置列间距
- (CGFloat)scrollBall:(BTScrollBallView *)scrollBall minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
return 0;
}
// 设置横向间距
- (CGFloat)scrollBall:(BTScrollBallView *)scrollBall minimumLineSpacingForSectionAtIndexPath:(NSIndexPath *)indexPath{
return 0;
}
// 设置号码球的Y值
- (CGFloat)scrollBall:(BTScrollBallView *)scrollBall insetSpaceingForSectionAtIndex:(NSInteger)section{
return 0;
}
// 设置号码球的X值
- (CGFloat)leadingOfSectionsInScrollBall:(BTScrollBallView *)scrollBall{
return 0;
}
3、创建数据且刷新数据
/// 点击屏幕设置数据且滚动
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
self.datas = [self makeDatas];;
[self.scrollBall scrollToBottomWithAnimate:YES];
}
// 创建二维数组
- (NSArray<NSArray<NSNumber*> *> *)makeDatas{
NSMutableArray * arr = [NSMutableArray array];
for (int i = 0; i<5; i++) {
NSInteger f = (arc4random() % 20);
NSNumber * las = @(0);
if (self.datas != nil) {
NSArray * obj = self.datas[i];
las = obj.lastObject;
}
NSArray * mu = [NSArray arrayWithFromValue:las.integerValue toValue:f maxValue:10];
[arr addObject:mu];
}
return arr;
}
实现方式
由于视图并不需要交互,所以我直接使用了CALayer作为号码球图层,通过CAScrollLayer添加一组号码球,就可以实现滚动效果。由于ScrollLayer自动识别边界,所以可以直接调用方法滚动到某点,滚动时再添加动画即可完成。
获取CALayer的方法
CALayer * layer = [self.dataSource scrollBall:self ballForRowAtIndexPath:indexPath];
[scrollLayer addSublayer:layer];
滚动方法
- (void)scrollPoint:(CGPoint)p animate:(BOOL)animate{
[self stopAnimate];
[CATransaction begin];
[CATransaction setDisableActions:!animate];
[CATransaction setAnimationDuration:animate?3:0];
[self scrollToPoint:p];
[CATransaction commit];
}
⚠️ 注意点
获取对象的代理方法是在完成添加到父视图后才获取,此时代理对象才有值;
/// UIView生命周期中的方法
- (void)didMoveToSuperview{
[super didMoveToSuperview];
[self createLayers];
}
SDK地址:BTScrollBallView
网友评论