我试图在uiscrollview中添加uiview的移动手势,但我无法禁用uiscrollview的srcoll事件。我在Main类中实现了UIScrollview和分页启用。在另一个类中,我在其中添加了uiview,为它添加了手势,但我不知道如何禁用uiscrollview的滚动。
请给我一些建议。提前谢谢。
答案 0 :(得分: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];
}
希望这个答案可以帮到你。