gpi*_*ler 1 uiscrollview uiviewcontroller ios
我有一个问题UIScrollView,如果我点击标签栏项目切换到另一个ViewController,然后返回到ViewController,UIScrollView我无法滚动到顶部.我必须在ViewControllers之间再次切换,然后UIScrollView正确显示内容.这个过程对用户来说真的很不舒服.这是我的代码:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self becomeFirstResponder]; // View as first responder
scrollView.scrollEnabled = YES;
[scrollView setUserInteractionEnabled:YES];
testLabel.text = @"there is a long, long text normally";
}
Run Code Online (Sandbox Code Playgroud)
我没有故意设置contentSize,因为UIScrollView根据此标签自动获取正确的高度.我的问题是,如果我向下滚动然后切换到另一个ViewController,当我再次回到此屏幕时,我无法再向上滚动到顶部.
一些进一步的信息:使用自动布局,层次结构是:ViewController - 视图 - UIScrollView - 标签,...
我一直在努力解决这个问题!不幸的是,我无法确切地知道发生了什么或导致了什么(苹果方面的错误?),但我创造了一个似乎相当有效的工作.
我正在做的是在viewWillDissapear方法中我将滚动视图边界高度位置保存在本地浮点变量中,然后将滚动视图完全重置到顶部.
然后在didLayoutSubviews方法中,我滚动回到保存的位置.
这是我的代码.
用于存储最后一个滚动值并延迟实例化的安装变量:
@property (nonatomic) float lastScrollHeight;
@synthesize lastScrollHeight = _lastScrollHeight;
-(float)lastScrollHeight{
if(!_lastScrollHeight) _lastScrollHeight = 0;
return _lastScrollHeight;
}
Run Code Online (Sandbox Code Playgroud)
在视图执行布局子视图后,滚动到保存的值(第一次为零):
-(void)viewDidLayoutSubviews{
[super viewDidLayoutSubviews];
[self.scrollView setContentOffset:CGPointMake(0.0f, self.lastScrollHeight) animated:NO];
}
Run Code Online (Sandbox Code Playgroud)
每次视图消失时,完全"重置"滚动视图:
-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
self.lastScrollHeight = self.scrollView.bounds.origin.y;
[self resetApplesBrokenScrollview];
}
-(void)resetApplesBrokenScrollview{
[self.scrollView setContentOffset:CGPointZero];
CGRect sFrame = self.scrollView.bounds;
sFrame.origin = CGPointZero;
self.scrollView.bounds = sFrame;
CGRect cFrame = self.contentView.frame;
cFrame.origin = CGPointZero;
self.contentView.frame = cFrame;
}
Run Code Online (Sandbox Code Playgroud)
这是我第一次回答有关Stack Overflow的问题!如果您发现我的答案有用,请点击左侧的灰色向上箭头.