0

我正在尝试使用分页构建一个简单的 UIScrollView 以在 3 个图像之间水平滚动。棘手的部分是我希望每个图像都可以点击并捕获点击事件。

我的技术是创建 3 个 UIButton,每个都包含 UIImage。给每个按钮一个标签并设置一个动作。

问题:我可以捕捉到点击事件 -它不可滚动!

这是我的代码:

- (void) viewDidAppear:(BOOL)animated {

    _imageArray = [[NSArray alloc] initWithObjects:@"content_01.png", @"content_02.png", @"content_03.png", nil];

    for (int i = 0; i < [_imageArray count]; i++) {
        //We'll create an imageView object in every 'page' of our scrollView.
        CGRect frame;
        frame.origin.x = _contentScrollView.frame.size.width * i;
        frame.origin.y = 0;
        frame.size = _contentScrollView.frame.size;

        //
        //get the image to use, however you want
        UIImage* image = [UIImage imageNamed:[_imageArray objectAtIndex:i]];

        UIButton* button = [[UIButton alloc] initWithFrame:frame];

        //set the button states you want the image to show up for
        [button setImage:image forState:UIControlStateNormal];
        [button setImage:image forState:UIControlStateHighlighted];

        //create the touch event target, i am calling the 'productImagePressed' method
        [button addTarget:self action:@selector(imagePressed:)
         forControlEvents:UIControlEventTouchUpInside];
        //i set the tag to the image #, i was looking though an array of them
        button.tag = i;

        [_contentScrollView addSubview:button];
    }

    //Set the content size of our scrollview according to the total width of our imageView objects.
    _contentScrollView.contentSize = CGSizeMake(_contentScrollView.frame.size.width * [_imageArray count], _contentScrollView.frame.size.height);

    _contentScrollView.backgroundColor = [ENGAppDelegate backgroundColor];
    _contentScrollView.delegate = self;
}
4

1 回答 1

1

好吧,既然UIButton是一个UIControl子类,它会“吃掉”你的滚动视图的触摸:

[UIScrollView touchesShouldCancelInContentView:]如果 view 不是 UIControl 对象,则默认返回值为 YES;否则,它返回 NO。

(来自https://developer.apple.com/library/ios/documentation/uikit/reference/UIScrollView_Class/Reference/UIScrollView.html#//apple_ref/occ/instm/UIScrollView/touchesShouldCancelInContentView :)

可以UIScrollView通过子类化和覆盖touchesShouldCancelInContentView:(和/或touchesShouldBegin:withEvent:inContentView:)来影响这一点。但是,对于您的用例,我首先不会使用按钮。为什么不直接在滚动视图中添加一个点击手势识别器并使用触摸点来确定哪个图像被点击了呢?这要容易得多,应该可以毫无问题地工作。

于 2013-10-06T21:20:09.283 回答