2013-10-06 167 views
0

我想要建立一个简单的UIScrollView与分页,以在3个图像之间水平滚动。 棘手的部分是,我希望每个图像可点击并捕捉点击事件。添加UIButtons作为子视图时UIScrollView不滚动

我的技巧是创建3个UIButton,每个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; 
} 
+0

您是否已通过代码确保_contentScrollView.contentSize是您的期望?我认为_contentScrollView.frame.size在这一点上计算不正确,所以你不会得到很好的价值。 – HalR

+0

我查过了,计算正确!让我这样说:如果我没有框架启动按钮(所以没有图片显示),然后我看到它滚动! – Shvalb

+0

是否有可能,如果我设置的按钮框架像ScrollView的确切大小,那么它完全阻止滚动,所以我没有得到滚动事件? – Shvalb

回答

1

好吧,既然UIButtonUIControl子类,它 “吃掉” 你的滚动视图的触摸:

[UIScrollView touchesShouldCancelInContentView:]默认返回值是YES如果视图不是UIControl对象;否则,它返回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:

可能影响这一点。但是,对于您的用例,我不会首先使用按钮。为什么不只是在滚动视图中添加轻击手势识别器并使用触点来确定哪个图像已被轻敲?这很容易,应该没有任何问题。

相关问题