尝试在iOS中使用gestureRecognizer正确移动UIImageView

时间:2013-06-20 15:51:21

标签: ios uitableview uiimageview uipangesturerecognizer

我有一个UIImageView,我试图使用UIPanGestureRecognizer对象移动。 UIImageView位于UITableView的顶部,用作滚动条。我想让用户在UITableView上向上或向下移动这个UIImageView,而不是侧身。为此,我实现了UIGestureRecognizerDelegate,我有以下方法:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {

     return YES;

}

- (void)panGestureDetected:(UIPanGestureRecognizer *)recognizer {

    NSLog(@"Do I get called?");
    //_startLocation is a property of type CGPoint that I declare in the .h file
    _startLocation = [recognizer locationInView:_imageView];

    NSLog(@"The point is: %d", _startLocation);

    CGRect frame = [_imageView frame];

    frame.origin.y += frame.origin.y - _startLocation.y;

    [_imageView setFrame: frame];

    _imageView.center = _startLocation;

} 

方法panGestureDetectedviewDidLoad调用,如下所示:

UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureDetected:)];
    panGesture.maximumNumberOfTouches = 1;
    panGesture.minimumNumberOfTouches = 1;
    panGesture.delegate = self;
    [_table addGestureRecognizer:panGesture];

不幸的是,当我尝试移动它时,我的UIImageView在屏幕上疯狂移动。我希望看到一个平滑滚动的UIImageView在用户拖动时向上/向下移动。谁能看到我做错了什么?

1 个答案:

答案 0 :(得分:1)

在你的处理程序方法中,只需保留此行并删除所有其他行。

_imageView.center.y = [recognizer locationInView:[_imageView superView]].y; 

您需要在superView中获取位置,而不是imageView本身。只需更改中心的y值。