从uiview转移到uiscrollview

时间:2015-01-20 02:49:23

标签: ios objective-c iphone uiview uiscrollview

我在UIView(红色)中有一个UIScrollview(带图像)。

UIView - {0,0,320,236} UIScrollview - {0,8,300,220}

enter image description here

enter image description here

在我的观点中,我接触到了。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{}

我需要将触摸从UIView转移到UIScrollview。 (例如,如果用户从uiview的右侧向左滑动,uiscrollview应与用户触摸同步滚动到左侧)。我可以知道该怎么做吗?

1 个答案:

答案 0 :(得分:1)

我们的想法是在UIView中获取对scrollView的引用,计算x touches delta并相应地调整scrollView的contentOffset属性。

所以,在你的UIView类中:

@implementation MyView{
  CGPoint _startPosition;
  CGPoint _previousPosition;
}

中初始化上述变量
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
  UITouch *touch = [touches anyObject];
  _startPosition = [touch locationInView:self];
  _previousPosition = _startPosition;
}

然后在你的touchesMoved:

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{

UITouch *touch = [touches anyObject];
CGPoint currentPosition = [touch locationInView:self.scrollView];


if(!CGPointEqualToPoint(_previousPosition, _startPosition)){
    CGFloat deltaX = _previousPosition.x-currentPosition.x;

    [UIView animateWithDuration:0.1 animations:^{
        //
        self.scrollView.contentOffset = CGPointMake(self.scrollView.contentOffset.x +
                                                    deltaX, self.scrollView.contentOffset.y);
    }];


}
_previousPosition = currentPosition;
}

在动画块中调整scrollView.contentOffset以使滚动平滑。

链接到工作项目:https://github.com/sliaquat/stack_overlfow_answer_28036976