Is there any way I can scroll UITextView from other view?

强颜欢笑 提交于 2019-12-11 23:20:34

问题


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.



来源:https://stackoverflow.com/questions/25533317/is-there-any-way-i-can-scroll-uitextview-from-other-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!