簡體   English   中英

按下UIButton時允許UIScrollView滾動

[英]allow UIScrollView to scroll when UIButton is pressed

我在UIScrollView里面有一個UIView,在UIView里面是一個按鈕。 問題是,當我按下該按鈕時,按住它(在這種情況下按下按鈕狀態)並嘗試滾動,我的滾動視圖不會滾動。 應該在哪個。 UIView中有一個手勢識別器,我試圖使用其中一個委托來滾動滾動視圖,如果我用手按下UIButton並滾動。 我該怎么做呢?

基本上總結一下,如果按下/按住按鈕,我需要將觸摸事件傳遞給滾動視圖。 如果它是按鈕的觸摸事件,那么顯然它應該觸發按鈕的動作而不是滾動。

老問題,但我剛才有這個問題,並認為人們會從答案中受益。 如果在UIScrollView中有UIControl,默認情況下滾動不會取消觸摸事件。 解決方案是將UIScrollView子類化為:

@implementation PaginationScrollView {}

- (id)init {
    self = [super init];
    if (self) {
        self.canCancelContentTouches = YES;
    }
    return self;
}

- (BOOL)touchesShouldCancelInContentView:(UIView *)view {
    return YES;
}

@end

如果視圖是UIControl,touchesShouldCancelInContentView的默認實現返回NO。

確保設置

yourScrollView.canCancelContentTouches = YES;

還是行不通? 因為它只取消觸摸而不是取消UIControlEvents,例如UIControlEventTouchUpInside

怎么解決? 將其添加到.m文件的頂部

@implementation UIScrollView (TouchesShouldCancelInContentView)

- (BOOL)touchesShouldCancelInContentView:(UIView *)view {
    return YES;
}

@end

您不需要為UIButton的簡單TouchUpInside操作添加UIGestureRecognizer,只需執行以下操作:

[button addTarget:self action:@selector(buttonSelect:) forControlEvents:UIControlEventTouchUpInside];

然后創建選擇器:

-(IBAction)buttonSelect:(id)sender{//do stuff here}

您可以嘗試使UIButton不可交互:

button.userInteractionEnabled = NO;

然后在按鈕上添加UITapGestureRecognizer:

UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(buttonPressed)];
[button addGestureRecognizer:recognizer];

這樣,按鈕將僅在觸摸事件時對其進行響應,所有其他事件將轉到滾動視圖。

設置userInteractionEnabled = NO可能會阻止UITapGestureRecognizer觸發其事件,在這種情況下,您可以將按鈕設置為UIView或UIImageView。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM