2010-03-01 45 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