在iOS中使用UIPanGestureRecognizer时,尝试限制UIImage的移动

时间:2013-09-23 20:39:34

标签: ios uitableview uiimage uipangesturerecognizer

我正在开发一个应用程序,我允许用户移动标尺以滚动UITableView。此刻,标尺移动得很好,除了我想将它的移动仅限制在UITableView的行上,而不是别的。不幸的是,此时用户可以从顶部滚动整个表格,并从表格底部到屏幕底部。我附上了一张图片来说明这一点:

enter image description here

以下是我的相关代码:

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

    CGPoint newCenter  = _imageView.center;

        newCenter.y = [recognizer locationInView:[_imageView superview]].y;

        if (newCenter.y - _imageView.frame.size.height / 2 < self.table.frame.origin.y)
            newCenter.y = self.table.frame.origin.y + _imageView.frame.size.height / 2;

        else if (newCenter.y + _imageView.frame.size.height / 2 > self.table.frame.origin.y + self.table.frame.size.height)
            newCenter.y = self.table.frame.origin.y + self.table.frame.size.height - _imageView.frame.size.height / 2;

        _imageView.center = newCenter;


        if ([recognizer state] == UIGestureRecognizerStateChanged) {

            if (newCenter.y == self.table.frame.origin.y + _imageView.frame.size.height / 2) {

                CGPoint topPoint = [recognizer locationInView:_table];
                NSIndexPath *nextRow = [_table indexPathForRowAtPoint:topPoint];
                int currentRow = nextRow.row;

                if (currentRow != 0) {

                    nextRow = [NSIndexPath indexPathForRow:currentRow-- inSection:0];

                    [UIView animateWithDuration:.3 animations:^{
                        [_table selectRowAtIndexPath:nextRow animated:NO scrollPosition:UITableViewScrollPositionBottom];

                    }];

                }


            }
            //below is the specific section where I believe is the issue
            else if (newCenter.y == self.table.frame.origin.y + self.table.frame.size.height - _imageView.frame.size.height / 2) {

                CGPoint bottomPoint = [recognizer locationInView:_table];
                NSIndexPath *nextRow = [_table indexPathForRowAtPoint:bottomPoint];
                int currentRow = nextRow.row;

                if (currentRow != [self.tireCode count]-1) {

                    nextRow = [NSIndexPath indexPathForRow:currentRow++ inSection:0];

                    [UIView animateWithDuration:.3 animations:^{
                        [_table selectRowAtIndexPath:nextRow animated:NO scrollPosition:UITableViewScrollPositionBottom];

                    }];

                }

            }

        }

正如我所说,我希望标尺只滚动UITableView的行,除此之外什么都没有。谁能看到我做错了什么?

感谢所有回复的人。

1 个答案:

答案 0 :(得分:0)

在分配超出范围的值之前,您应该检查newCenter.y的值。 为其定义最小值和最大值。

float calculatedY = self.table.frame.origin.y + _imageView.frame.size.height / 2;

calculatedY = MAX(calculatedY, MINIMUM_VALUE_HERE);
calculatedY = MIN(calculatedY, MAXIMUM_VALUE_HERE);

newCenter.y = calculatedY;