为 UIScrollView 添加手势事件,通过屏幕宽度与 UIScrollView 的偏移量 contentOffset 的方式获取对应的当前滚动页面点击事件,具体 code 如下:
首先,创建 UIScrollView 实现简易的基础控件并绑定手势事件进行监听
#pragma mark - ************************************ UI
- (UIScrollView *)carouselScrView {
if (!_carouselScrView) {
NSInteger scrViewHeight = SCREEN_HEIGHT / 3;
UIScrollView *scrView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, scrViewHeight)];
scrView.backgroundColor = [UIColor lightGrayColor];
scrView.delegate = self;
scrView.pagingEnabled = YES;// 设置是否可以分页滚动
scrView.bounces = NO;// 设置不能滚动到边界外面,当然你也可以只设置某一个方向滚动到边界外面(这里指的是手拖)
scrView.showsHorizontalScrollIndicator = NO;// 设置是否显示水平和垂直显示条
scrView.showsVerticalScrollIndicator = NO;
NSArray *arrData = @[@"1",@"2",@"3",@"4"];
for (NSInteger i = 0; i < arrData.count; i++) {
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(i * SCREEN_WIDTH, 0, SCREEN_WIDTH, scrViewHeight)];
imgView.userInteractionEnabled = YES;
imgView.image = [[UIImage imageNamed:arrData[i]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
// 绑定手势监听
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapHotScrWithEvent:)];
tapGesture.delegate = self;
tapGesture.numberOfTouchesRequired = 1;// 设计点按次数,默认为1
tapGesture.numberOfTapsRequired = 1;// 点按手指数
[imgView addGestureRecognizer:tapGesture];
[scrView addSubview:imgView];
}
scrView.contentSize = CGSizeMake(arrData.count * SCREEN_WIDTH, scrViewHeight);
_carouselScrView = scrView;
}
return _carouselScrView;
}
其次,处理绑定的手势事件 action
#pragma mark - ************************************ Event
- (void)tapHotScrWithEvent:(UITapGestureRecognizer *)tap {
// 屏幕的偏移量
CGFloat x = self.carouselScrView.contentOffset.x;
// 屏幕的宽
CGFloat w = CGRectGetWidth(self.carouselScrView.frame);
// 偏移量除以宽,得到当前的页数
NSInteger curPage = x/w;
NSLog(@"轮播图被点击了:%ld", (long)curPage);
}
最后,基础的声明、设置代理和调用实现的部分
@interface YHDemoVC () <UIScrollViewDelegate, UIGestureRecognizerDelegate>
// 轮播图
@property (nonatomic, strong) UIScrollView *carouselScrView;
@end
@implementation YHDemoVC
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self.view addSubview:self.tabView];
}
以上便是此次分享的全部内容,希望能对大家有所帮助!
网友评论