UIScrollView でスクロールの方向を見つけるには? 質問する

UIScrollView でスクロールの方向を見つけるには? 質問する

水平スクロールのみが許可されている がありUIScrollView、ユーザーがどの方向 (左、右) にスクロールするかを知りたいです。 をサブクラス化してUIScrollView、メソッドをオーバーライドしましたtouchesMoved

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesMoved:touches withEvent:event];

    UITouch *touch = [touches anyObject];
    float now = [touch locationInView:self].x;
    float before = [touch previousLocationInView:self].x;
    NSLog(@"%f %f", before, now);
    if (now > before){
        right = NO;
        NSLog(@"LEFT");
    }
    else{
        right = YES;
        NSLog(@"RIGHT");

    }

}

しかし、移動したときにこのメソッドがまったく呼び出されないことがあります。どう思いますか?

ベストアンサー1

方向の決定は非常に簡単ですが、ジェスチャの過程で方向が何度も変わる可能性があることに留意してください。たとえば、ページングがオンになっているスクロール ビューがあり、ユーザーがスワイプして次のページに移動する場合、最初の方向は右方向になる可能性がありますが、バウンスがオンになっている場合は、一時的に方向が定まらず、その後一時的に左方向に移動します。

方向を決定するには、デリゲートを使用する必要がありますUIScrollView scrollViewDidScroll。このサンプルでは、​​現在のコンテンツのオフセットを前のコンテンツと比較するために使用する という名前の変数を作成しましたlastContentOffset。大きい場合は、scrollView は右にスクロールしています。小さい場合は、scrollView は左にスクロールしています。

// somewhere in the private class extension
@property (nonatomic, assign) CGFloat lastContentOffset;

// somewhere in the class implementation
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    ScrollDirection scrollDirection;

    if (self.lastContentOffset > scrollView.contentOffset.x) {
        scrollDirection = ScrollDirectionRight;
    } else if (self.lastContentOffset < scrollView.contentOffset.x) {
        scrollDirection = ScrollDirectionLeft;
    }

    self.lastContentOffset = scrollView.contentOffset.x;

    // do whatever you need to with scrollDirection here.    
}

方向を定義するために次の列挙型を使用しています。最初の値を ScrollDirectionNone に設定すると、変数を初期化するときにその方向をデフォルトにするという追加の利点があります。

typedef NS_ENUM(NSInteger, ScrollDirection) {
    ScrollDirectionNone,
    ScrollDirectionRight,
    ScrollDirectionLeft,
    ScrollDirectionUp,
    ScrollDirectionDown,
    ScrollDirectionCrazy,
};

おすすめ記事