谁能准确描述 -[UIScrollView zoomToRect:animated:]
的行为?这种方法似乎确实做了一些复杂的事情,但 Apple 的文档非常稀少。
当内容大小在宽度和/或高度上小于 ScrollView 的大小时,此方法出现不可预测的行为。在某些情况下,此方法会导致 ScrollView 在本应为 0 的情况下具有负的内容偏移量。传递略有不同的矩形后,它会将内容偏移量保留为 0,就像我期望的那样。
为了演示这种奇怪的行为,我设置了一个示例项目,其中包含一个大小为 (200, 200) 的 ScrollView ,其中包含一个大小为 (100, 100) 的内容 View 。我希望内容 View 的缩放到 rect ((0, 0), (200, 200)) 应该将内容留在左上角(即什么都不应该发生).但是,它实际上导致内容滚动到 ScrollView 边界的右下角(内容偏移量(-100,-100))。为什么会这样?
这是我的示例项目中的代码:
@implementation RootViewController
- (void)loadView {
self.view = [[UIView alloc] init];
self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
self.scrollView.delegate = self;
self.scrollView.backgroundColor = [UIColor whiteColor];
self.scrollView.minimumZoomScale = .5;
self.scrollView.maximumZoomScale = 4;
self.contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
self.contentView.backgroundColor = [UIColor redColor];
[self.contentView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap)]];
[self.scrollView addSubview:self.contentView];
self.scrollView.contentSize = self.contentView.frame.size;
[self.view addSubview:self.scrollView];
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
return self.contentView;
}
- (void)handleTap {
[self.scrollView zoomToRect:CGRectMake(0, 0, 200, 200) animated:YES]; // Try changing to 199, 199 to get completely different behavior
}
@end
感谢您的任何见解!现在我猜测 UIScrollView
并不是为了显示小于其自身大小的内容而设计的。我的用例是,我可能有一个比 ScrollView 宽但高度较短的内容 View ,我需要能够以编程方式滚动到该内容 View 的右端或左端。
最佳答案
除非有人有更好的答案,否则我将得出结论,当生成的 contentSize
小于 时,调用
任一维度的大小。换句话说,如果你想安全的话,内容应该比 ScrollView 大。-zoomToRect:animated:
会产生未定义的结果>bounds
关于ios - -[UIScrollView zoomToRect :animated:] weird behavior when contentSize < bounds. 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23900933/