2010-03-01 107 views
3

出于某种原因,我的viewController的addBook方法中初始化的按钮将不响应触摸。我分配给它的选择器从不触发,也不会在点击图像时出现UIControlStateHighlighted图像。iPhone:添加按钮scrollview使按钮无法进入交互

是否有东西在它们到达UIButton之前拦截触摸,或者是它的交互性以某种方式被我对它做的事情所禁用?

- (void)viewDidLoad { 

    ... 

    _scrollView.contentSize = CGSizeMake(currentPageSize.width, currentPageSize.height); 
    _scrollView.showsHorizontalScrollIndicator = NO; 
    _scrollView.showsVerticalScrollIndicator = NO; 
    _scrollView.scrollsToTop = NO; 
    _scrollView.pagingEnabled = YES; 

    ... 
} 

- (void)addBook { 
    // Make a view to anchor the UIButton 
    CGRect frame = CGRectMake(0, 0, currentPageSize.width, currentPageSize.height); 
    UIImageView* bookView = [[UIImageView alloc] initWithFrame:frame]; 

    // Make the button 
    frame = CGRectMake(100, 50, 184, 157); 
    UIButton* button = [[UIButton alloc] initWithFrame:frame]; 
    UIImage* bookImage = [UIImage imageNamed:kBookImage0]; 

    // THIS SECTION NOT WORKING! 
    [button setBackgroundImage:bookImage forState:UIControlStateNormal]; 
    UIImage* bookHighlight = [UIImage imageNamed:kBookImage1]; 
    [button setBackgroundImage:bookHighlight forState:UIControlStateHighlighted]; 
    [button addTarget:self action:@selector(removeBook) forControlEvents:UIControlEventTouchUpInside]; 

    [bookView addSubview:button]; 
    [button release]; 
    [bookView autorelease]; 

    // Add the new view/button combo to the scrollview. 
    // THIS WORKS VISUALLY, BUT THE BUTTON IS UNRESPONSIVE :(
    [_scrollView addSubview:bookView]; 
} 

- (void)removeBook { 
    NSLog(@"in removeBook"); 
} 

视图层次看起来像这样在Interface Builder:

UIWindow 
UINavigationController 
    RootViewController 
     UIView 
      UIScrollView 
      UIPageControl 

想必这样一旦addBook方法运行:

UIWindow 
UINavigationController 
    RootViewController 
     UIView 
      UIScrollView 
       UIView 
        UIButton 
      UIPageControl 

回答

7

UIScrollView可能会捕获所有的触摸事件。

也许尝试以下的组合:

_scrollView.delaysContentTouches = NO; 
_scrollView.canCancelContentTouches = NO; 

bookView.userInteractionEnabled = YES; 
+0

谢谢,MrMarge。后面的建议奏效了。 – clozach

+0

userInteractionEnabled对于我将UIButton作为子视图添加到的视图而言是NO。这是原因,而不是其他2个设置。 – Alyoshak

4

尽量去除[图书查看自动释放];并做到这一点是这样的:

// Add the new view/button combo to the scrollview. 
// THIS WORKS VISUALLY, BUT THE BUTTON IS UNRESPONSIVE :(
[_scrollView addSubview:bookView]; 
[bookView release]; 

_scrollView.canCancelContentTouches = YES;应该做的伎俩

delaysContentTouches - 是决定滚动视图是否延迟触摸下手势的处理布尔值。如果此属性的值为YES,那么滚动视图会延迟处理触摸手势,直到它可以确定滚动是否为意图。如果值为NO,滚动视图会立即调用touchesShouldBegin:withEvent:inContentView :.默认值是YES。

canCancelContentTouches - 是一个布尔值,用于控制内容视图中的触摸是否始终导致跟踪。如果此属性的值为YES,并且内容中的视图已开始跟踪触摸它的手指,并且用户拖动手指足以启动滚动,则视图将接收touchesCancelled:withEvent:消息,滚动视图处理触摸滚动。如果此属性的值为NO,则内容视图开始追踪后,无论手指移动如何,滚动视图都不会滚动。

+0

糟糕。是的,我没有正确使用autorelease ......浪费。谢谢,SorinA。 – clozach