Setting a new contentSize to a UIScrollView causes it to scroll back to point x:0 y:0
In my app I have some 开发者_StackOverflow中文版logic that changes the UIScrollView
's contentSize
dynamically. The problem I'm running into is that when I change the contentSize it sets the contentOffset
to CGPointZero
or something like that.
I guess you can't set contentSize
to be in the middle of the UIScrollView
. Any ideas on how to get this to work?
In other words I want to change the contentSize
of my UIScrollView
half way and keep its contentOffset
.
thanks in advance,
fbr
In my application, i had a UIViewController
which had a UIScrollView
as its root subview. That scrollView contains a UIView
which acts a a container for a UITextView
i had embedded.
Entering a long enough string would cause the textView to expand, subsequently changing the contentSize
of the scrollView causing it to reset it's content offset to 0. Looking at the stack trace i was able to see _adjustContentOffsetIfNecessary
attempts to adjust the content offset immediately after a contentSize change.
I created a subclass of UIScrollView
that blocks _adjustContentOffsetIfNecessary
initial attempt to adjust the offset.
class CustomScrollView: UIScrollView {
private var oldContentSize: CGSize = .zero
override var contentOffset: CGPoint {
set {
if oldContentSize == contentSize {
super.contentOffset = newValue
} else {
super.contentOffset = super.contentOffset
oldContentSize = contentSize
}
}
get {
return super.contentOffset
}
}
}
When the contentSizes are the same, we adjust the offset as normal. If it differs, we keep the offset the same and update oldContentSize to its new size so the next time around it's receptive to changing its offset.
As you've already seen, you can't do this by changing contentSize
, but you can fake it by changing the contentOffset
and moving your subviews around. An example of this in the DTInfiniteGridView
class of Daniel Tull's DTKit library.
setContentSize:
of UIScrollView will set its contentOffset( _adjustContentOffsetIfNecessary
, an internal method is called,which does the mysterious offset change on your scrollview.)
One way to set the required content offset is to do setContentOffset:reqiredOffset animation:NO
on the scrollview.
(requiredOffset is calculated for new contentSize).
I think you can just trick this by saving your current contentOffset
and after you set the new contentSize
, you can just use the setContentOffset:animated:
to return the scroll where it was. Hope this helps.
I don't know about which is the method will used,
- (void)viewDidLoad {
[super viewDidLoad];
srcv.contentSize = ?;
}
Here what will come and replace with "?" to scroll the simulator
精彩评论