1

我正在使用 UIScroll View 制作具有分页功能的类似画廊的 ui。基本上是这样的:

在此处输入图像描述

由于我需要分页,所以我将scrollview的宽度设置为单个页面的宽度,在我的示例中为粉红色矩形的宽度。

但我想要两个额外的东西:

  1. 点击黄色或蓝色区域会将相应的矩形带到中心。
  2. 可以在黄色或蓝色区域(滚动视图之外)滚动/滑动,这意味着屏幕的整个宽度都是可滚动的。

我关注了这个线程并添加了- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event. 但是这样做,我只能实现我的第二个目标。当我设置选择器或委托处理黄色和蓝色的点击反应时,它不起作用。有什么想法吗?

4

1 回答 1

1

您引用的那个答案是我最喜欢的答案之一。它没有考虑您的第一个要求,但我认为只需添加一个轻击手势识别器,它就可以非常巧妙地处理它。

在您的“ClipView”上创建它:

UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
[self.myClipView addGestureRecognizer:tapGR];
// myClipView is the view that contains the paging scroll view

- (void)tap: (UITapGestureRecognizer *)gr {
    // there are a few challenges here:
    // 1) get the tap location in the correct coordinate system
    // 2) convert that to which "page" was tapped
    // 3) scroll to that page
}

挑战 1) 很容易感谢手势识别器,它回答locationInView:

CGPoint location = [gr locationInView:self.scrollView]; 

对于挑战 2),我们需要确定您的滚动视图中的哪个页面被点击了。给定页面宽度,这可以通过非常简单的算术来完成。

// assuming you have something like this
#define kPAGE_WIDTH    // some float

// page is just how many page-width's are represented by location.y
NSInteger page = floor(location.y/kPAGE_WIDTH);

现在,挑战 3) 现在很容易,因为我们可以直接将页面更改为它的滚动位置......

CGFloat y = page * kPAGE_WIDTH;
[self.scrollView setContentOffset:CGPointMake(y, 0.0f) animated:YES];

或者,全部在一块代码中......

- (void)tap: (UITapGestureRecognizer *)gr {
    CGPoint location = [gr locationInView:self.scrollView]; 
    NSInteger page = floor(location.y/kPAGE_WIDTH);
    CGFloat y = page * kPAGE_WIDTH;
    [self.scrollView setContentOffset:CGPointMake(y, 0.0f) animated:YES];
}

编辑

您可能还想从手势识别器中排除“当前页面”区域。这只是通过在 tap 方法中限定测试来完成的。

唯一的技巧是在与滚动视图的框架相同的坐标系中获取点击位置,即剪辑视图......

CGPoint locationInClipper = [gr locationInView:gr.view]; 

SDK 提供了一个很好的测试方法......

BOOL inScrollView = [self.scrollView pointInside:locationInClipper withEvent:nil];

所以...

- (void)tap: (UITapGestureRecognizer *)gr {
    CGPoint locationInClipper = [gr locationInView:gr.view]; 
    BOOL inScrollView = [self.scrollView pointInside:locationInClipper withEvent:nil];

    if (!inScrollView) {
        CGPoint location = [gr locationInView:self.scrollView]; 
        NSInteger page = floor(location.y/kPAGE_WIDTH);
        CGFloat y = page * kPAGE_WIDTH;
        [self.scrollView setContentOffset:CGPointMake(y, 0.0f) animated:YES];
    }
}
于 2016-08-11T22:56:37.257 回答