I have a UITextView
and a simple blank view with UIPanGestureRecognizer
in it. The idea behind this was the following: I make a pan gesture in blank view, gesture recognizer detects it and scrolls the text view (by scrollToVisibleRect
or smth like that). Is there any other way? I am asking because this is not resolved yet.
问题:
回答1:
You can set the content offset of your textView, just like any other scrollView. Try something like this:
- (void)handlePan:(UIPanGestureRecognizer *)pan
{
if (pan.state == UIGestureRecognizerStateChanged) {
CGPoint offset = self.textView.contentOffset;
offset.y += [pan translationInView:pan.view].y;
self.textView.contentOffset = offset;
}
[pan setTranslation:CGPointZero inView:pan.view];
}
I haven't tested this, so there might be some small issues. This should at least get you pointed in the right direction. Let me know if you have updates/questions.
回答2:
Basically, Logan's answer is right. Although, I would like to add this: You need to subtract(not add) the y component of translation. So the code should look like this:
currentOffset.y -= [pan translationInView:pan.view].y;
And then you must prevent contentOffset
's being more than your textView's contentSize.height
.Just add this:
CGFloat minOffset = 0.0;
CGFloat maxOffset = self.myTextView.contentSize.height - self.myTextView.bounds.size.height;
self.myTextView.contentOffset = CGPointMake(0,fmax(minOffset, fmin(currentOffset.y, maxOffset)));
And yes,this line is VERY important
`[gestureRecognizer setTranslation:CGPointZero inView:gestureRecognizer.view];`
Why? Apple says in the :
- (CGPoint)translationInView:(UIView *)view
The x and y values report the total translation over time. They are not delta values from the last time that the translation was reported. Apply the translation value to the state of the view when the gesture is first recognized—do not concatenate the value each time the handler is called.
For further info, you'd better read this.