ios - 如何在 uiscrollview ios 中向 uiview 添加拖动手势

标签 ios objective-c iphone uiview uiscrollview

我试图在 uiscrollview 中添加 uiview 的移动手势,但我无法禁用 uiscrollview 的 srcoll 事件。我已经在主类中实现了带有分页功能的 UIScrollview。在另一个类中,我在其中添加了 uiview,为其添加了手势,但我不知道如何禁用 uiscrollview 的滚动。

请给我一些建议。提前致谢。

最佳答案

您需要从 UIView 类与其中的手势进行通信,方法是委托(delegate)给主类,要求 ScrollView 停止滚动,然后再启用它。我附上了代码。

你的 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];
        }
    }
}

包含 ScrollView 的主类文件。

- (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];
}

希望这个回答对你有帮助。

关于ios - 如何在 uiscrollview ios 中向 uiview 添加拖动手势,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25585671/

相关文章:

ios - 按钮操作不适用于 View 上的按钮

iphone - iOS:从图像列表创建视频文件时 VideoToolBox 内存泄漏

iphone - 以编程方式,在iphone中进行调用转移

ios - 是否可以在没有键盘的情况下选择 UITextField?

ios - XCode 更新帧扭曲 View 但在模拟器上看起来很棒

objective-c - 在 OSX 中创建许可协议(protocol)屏幕

ios - 使用 indexpath.row 引用从 JSON 对象数组中获取对象

javascript - iOS WebView Javascript

iphone - 由于 glGetString 应用程序崩溃

iphone - 从麦克风移动 Safari 录音