【问题标题】:Need to restrict movement of UIImageView to region covered by UITableView using UIPanGestureRecognizer in iOS需要在 iOS 中使用 UIPanGestureRecognizer 将 UIImageView 的移动限制在 UITableView 覆盖的区域
【发布时间】:2013-06-20 18:53:05
【问题描述】:

我目前正在我的应用程序中使用 UIPanGestureRecognizer 对象移动 UIImageView。目前,这个 UIImageView 在我的屏幕上很好地上下移动。但是,我现在想做的是将 UIImageView 的移动边界限制在位于屏幕中间的 UITableView 所覆盖的区域内。我想将此移动限制在 UITableView 的上下边界。这是我控制 UIImageView 移动的相关方法:

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

    _startLocation = [recognizer locationInView:_imageView];

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

    CGPoint newCenter  = _imageView.center;

    newCenter.y = [recognizer locationInView:[_imageView superview]].y;
//this is where I figure I need to include an if statement to perform a check to see if the location is within the desired region

    _imageView.center = newCenter;


}

我意识到我需要在我的方法中包含一个“if”语句来检查我的 UIImageView 是否在我想要的区域内,但问题是我不确定如何检查这一点。有人可以帮我吗?

【问题讨论】:

    标签: ios uitableview uiimageview uipangesturerecognizer


    【解决方案1】:

    您应该使用translationInView 方法(documentation)。

    这将返回用户将图像移动到的位置的CGPoint。将图像视图的原始位置与平移进行比较。如果平移太大以至于图像视图会移动到所需区域之外,请不要移动它。

    代码应该是这样的(我想你可以直接把它放进去):

    CGPoint translation = [recognizer translationInView:_imageView.superview];
    [recognizer setTranslation:CGPointMake(0, 0) inView:_imageView.superview];
    
    CGPoint center = recognizer.view.center;
    center.y += translation.y;
    if (center.y < _table.frame.origin.y 
        || center.y > _table.frame.size.height) {
               return;
    }
    recognizer.view.center = center;
    

    请参阅 this question 了解替代实现。

    【讨论】:

    • 非常感谢您的解决方案。我确实有一个后续问题要问你。我的表视图 (_table) 和我的 UIImageView (_imageView) 都附加到父/超级视图。因此,我是否将 _imageView.superview 替换为 _table?
    • 我会将 _imageView.superview.frame.origin.y 替换为 _table.frame.origin.y 并将 _imageView.frame.size.height 替换为 _table.frame.size.height。让我知道这是否有效
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多