首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当将UIScrollView添加为子视图时,UIButtons不会滚动

当将UIScrollView添加为子视图时,UIButtons不会滚动
EN

Stack Overflow用户
提问于 2013-10-06 19:41:48
回答 2查看 1.5K关注 0票数 1

我试图构建一个简单的UIScrollView,分页到3个图像之间水平滚动。棘手的部分是,我希望每个图像将是可点击和捕捉点击事件。

我的技术是创建3个UIButtons,每个UIImage由UIImage组成。给每个按钮一个标签并设置一个动作。

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

这是我的代码:

代码语言:javascript
复制
- (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;
}
EN

回答 2

Stack Overflow用户

发布于 2013-10-06 21:20:09

因为UIButton是一个UIControl子类,所以它“吞噬”了滚动视图的触感:

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

(来自ref/occ/instm/UIScrollView/touchesShouldCancelInContentView:)

您可以通过子类UIScrollView和覆盖touchesShouldCancelInContentView: (和/或touchesShouldBegin:withEvent:inContentView:)来影响这一点。但是,对于您的用例,我首先不会使用按钮。为什么不添加一个点击手势识别器到滚动视图,并使用触摸点,以确定哪个图像已被点击?这要容易得多,而且应该没有任何问题。

票数 1
EN

Stack Overflow用户

发布于 2022-04-17 09:32:46

这完全解决了这个问题:

代码语言:javascript
复制
scrollview.panGestureRecognizer.delaysTouchesBegan = YES;

https://stackoverflow.com/users/904365/kjuly在本主题中提供了正确的答案:ScrollView/TableView with UIControl/UIButton subviews not scrollable under iOS 8

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19213118

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档