IOS 仿时光网选票UI实例代码

2020-01-18 15:42:31王振洲

一、项目简介

该项目利用UIScrollView的各种滚动事件的监听,仿造时光网选择电影票的UI而开发的一个自定义View。使用简单,可扩展性很强。具备点击每个Item进行选票功能,选票居中功能,滑动时自动选择距离中间最近的View处于选中状态,而且对于滑动时松开手的时候是否有初始速度进行了区分处理。案例演示如下:<br/>

IOS,仿时光网选票UI,选票UI,时光网选票

仿时光网选票UI

二、项目讲解

1、初始化UIScrollView中每个Item的View,把每个View放到_viewArray数组中,方便接下来的定位和管理。每一个View中包含一个UIImageView,把每一个UIImageView放在_imageViewArray数组中,方便接下来的进行随着滑动的放大和缩小操作。


-(instancetype)initViewWithImageArray:(NSArray *)imageArray{
if (!imageArray) {
return nil;
}
if (imageArray.count<1) {
return nil;
}

NSInteger totalNum = imageArray.count;
self = [super initWithFrame:CGRectMake(0, 40, SCREEN_WIDTH, 120)];
if (self) {
_scrollview = [[UIScrollView alloc] initWithFrame:self.bounds];
_scrollview.contentSize = CGSizeMake(LEFT_SPACE*2+SELECT_VIEW_WIDTH+(totalNum-1)*NORMAL_VIEW_WIDTH+(totalNum-1)*ITEM_SPACE, 120);
_scrollview.delegate = self;
_scrollview.showsHorizontalScrollIndicator = NO;
_scrollview.decelerationRate = UIScrollViewDecelerationRateFast;
[self addSubview:_scrollview];

UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(-SCREEN_WIDTH, 0, _scrollview.contentSize.width+SCREEN_WIDTH*2, _scrollview.contentSize.height-20)];
backView.backgroundColor = [UIColor lightGrayColor];
[_scrollview addSubview:backView];

_imageViewArray = [NSMutableArray array];
_viewArray = [NSMutableArray array];

CGFloat offsetX = LEFT_SPACE;
for (int i=0; i<totalNum; i++) {

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(offsetX, 0, NORMAL_VIEW_WIDTH, NORMAL_VIEW_HEIGHT)];
[_scrollview addSubview:view];
[_viewArray addObject:view];
offsetX += NORMAL_VIEW_WIDTH+ITEM_SPACE;


CGRect rect;
if (i==0) {
rect = CGRectMake(-(SELECT_VIEW_WIDTH-NORMAL_VIEW_WIDTH)/2, 0, SELECT_VIEW_WIDTH, SELECT_VIEW_HEIGHT);
}else{
rect = CGRectMake(0, 0, NORMAL_VIEW_WIDTH, NORMAL_VIEW_HEIGHT);
}
UIImageView *imageView = [[UIImageView alloc] initWithFrame:rect];
imageView.image = imageArray[i];
imageView.tag = i;
imageView.userInteractionEnabled = YES;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickImage:)];
[imageView addGestureRecognizer:tap];
[view addSubview:imageView];
[_imageViewArray addObject:imageView];
}

}
return self;
}

2、在滑动的过程中,我们实时的需要改变计算哪一个Item距离中间最近,在过渡到最中间的过程中,选中的Item距离中间越近,选中Item的frame越大,反则越小。