UIScrollView 在 contentSize 改变时调整 contentOffset

时间:2022-10-27
本文介绍了UIScrollView 在 contentSize 改变时调整 contentOffset的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在调整详细视图控制器的状态,就在它被推送到 navigationController 之前:

I am adjusting a detail view controller's state, just before it is pushed on a navigationController:

[self.detailViewController detailsForObject:someObject];
[self.navigationController pushViewController:self.detailViewController
                                     animated:YES];

DetailViewController 中有一个滚动视图.我根据传递的对象调整了哪些内容的大小:

In the DetailViewController a scrollView resides. Which content I resize based on the passed object:

- (void)detailsForObject:(id)someObject {
    // set some textView's content here
    self.contentView.frame = <rect with new calculated size>;

    self.scrollView.contentSize = self.contentView.frame.size;
    self.scrollView.contentOffset = CGPointZero;
}

现在,这一切正常,但是在 navigationController 的滑入动画期间,scrollView 会调整它的 contentOffset.contentOffset 将设置为最后一个 contentSize 和新计算的值之间的差异.这意味着第二次打开 detailsView 时,详细信息将滚动到某个不需要的位置.即使我将 contentOffset 明确设置为 CGPointZero.

Now, this all works, but the scrollView adjusts it's contentOffset during the navigationController's slide-in animation. The contentOffset will be set to the difference between the last contentSize and the new calculated one. This means that the second time you open the detailsView, the details will scroll to some unwanted location. Even though I'm setting the contentOffset to CGPointZero explicitly.

我发现在-viewWillAppear中重置contentOffset没有效果.我能想到的最好办法是重置 viewDidAppear 中的 contentOffset,导致内容明显上下移动:

I found that resetting the contentOffset in - viewWillAppear has no effect. The best I could come up with is resetting the contentOffset in viewDidAppear, causing a noticeable up and down movement of the content:

- (void)viewDidAppear:(BOOL)animated {
    self.scrollView.contentOffset = CGPointZero;
}

有没有办法防止 UIScrollView 在其 contentSize 更改时调整其 contentOffset?

Is there a way to prevent a UIScrollView from adjusting its contentOffset when its contentSize is changed?

推荐答案

在使用 UINavigationController 推送包含 UIScrollViewUIViewController 时发生.

Occurs when pushing a UIViewController containing a UIScrollView using a UINavigationController.

iOS 11+

解决方案 1(Swift 代码):

scrollView.contentInsetAdjustmentBehavior = .never

解决方案 2(故事板)

iOS 7

解决方案 1(代码)

设置 @property(nonatomic, assign) BOOL automaticallyAdjustsScrollViewInsetsNO.

解决方案 2(故事板)

取消选中调整滚动视图插图

iOS 6

解决方案(代码)

viewWillLayoutSubviews中设置UIScrollView的属性contentOffsetcontentInset.示例代码:

Set the UIScrollView's property contentOffset and contentInset in viewWillLayoutSubviews. Sample code:

- (void)viewWillLayoutSubviews{
  [super viewWillLayoutSubviews];
  self.scrollView.contentOffset = CGPointZero;
  self.scrollView.contentInset = UIEdgeInsetsZero;
}

这篇关于UIScrollView 在 contentSize 改变时调整 contentOffset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一条:带有自动布局的程序化 UIScrollview 下一条:UIScrollView 的灵敏度/滚动速度与分页

相关文章

最新文章