2014-08-30 95 views
0

我試圖在uiscrollview中添加uiview的移動手勢,但是我無法禁用uiscrollview的srcoll事件。我在Main類中實現了帶有分頁啓用的UIScrollview。在另一個類中,我添加了uiview,爲它添加手勢,但我不知道如何禁用uiscrollview的滾動。如何在uiscrollview中向uiview添加拖動手勢ios

請給我一些建議。提前致謝。

回答

1

您需要通過委託給主類的UIView類與其中的手勢進行通信,請求滾動視圖以停止滾動,然後啓用它。我已經附上了代碼。

你UIView.h文件

@protocol MyUIViewProtocol <NSObject> 

- (void)setScrollViewScrollEnabled:(BOOL)enabled; 

@end 

@interface MyUIView : UIView 

@property (weak, nonatomic) id<MyUIViewProtocol> delegate; 

@end 

你UIView.m文件

@implementation MyUIView 

- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
     // Initialization code 

     [self setBackgroundColor:[UIColor redColor]]; 
     UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureMade:)]; 
     [self addGestureRecognizer:panGesture]; 
    } 
    return self; 
} 

- (void)panGestureMade:(UIPanGestureRecognizer *)recognizer 
{ 
    CGPoint pointsToMove = [recognizer translationInView:self]; 
    [self setCenter:CGPointMake(self.center.x + pointsToMove.x, self.center.y + pointsToMove.y)]; 
    [recognizer setTranslation:CGPointZero inView:self]; 

    //Disable the scroll when gesture begins and enable the scroll when gesture ends. 
    if (self.delegate && [self.delegate respondsToSelector:@selector(setScrollViewScrollEnabled:)]) { 
     if (recognizer.state == UIGestureRecognizerStateBegan) { 
      [self.delegate setScrollViewScrollEnabled:NO]; 
     } 
     else if (recognizer.state == UIGestureRecognizerStateCancelled || recognizer.state == UIGestureRecognizerStateEnded) { 
      [self.delegate setScrollViewScrollEnabled:YES]; 
     } 
    } 
} 

主類文件與它滾動視圖。

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 568)]; 
    [self.scrollView setBackgroundColor:[UIColor yellowColor]]; 
    [self.scrollView setPagingEnabled:YES]; 
    [self.scrollView setContentSize:CGSizeMake(320 * 3, 568)]; 
    [self.view addSubview:self.scrollView]; 

    MyUIView *view = [[MyUIView alloc] initWithFrame:CGRectMake(40, 100, 100, 100)]; 
    view.delegate = self; 
    [self.scrollView addSubview:view]; 
} 

- (void)setScrollViewScrollEnabled:(BOOL)enabled 
{ 
    [self.scrollView setScrollEnabled:enabled]; 
} 

希望這個答案可以幫助你。

相關問題