今天做了一个ScrollView的小例子(我的环境Xcode5.0.2 IOS7),结果发现无法滚动,即使设置了scrollView的contentSize还是不行,于是研究了一番,最终找到了解决方案:
在ios6之前,因为Xcode没有Autolayout的机制,所以直接使用scrollView,设置它的contentSize即可正常滚动
在ios6之后,因为Xcode引入了Autolayout的机制,所以我们设置的contentSize被修改为适合屏幕大小的值,也就是说自适应啦,因此无法滚动,解决方案如下:
直接去掉scrollView的Autolayout即可,但是这种方式不完美,毕竟Autolayout是官方推荐的,轻易去掉会引起其他问题,因此慎用。
在viewController中重载 - (void)viewDidAppear:(BOOL)animated 方法,并且设置contentSize,代码如下:
1 #import "ImaginariumViewController.h"
2
3 @interface ImaginariumViewController ()
4 @property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
5 @property (weak, nonatomic) IBOutlet UIImageView *imageView;
6 @end
7
8 @implementation ImaginariumViewController
9
10 - (void)viewDidAppear:(BOOL)animated
11 {
12 [super viewDidAppear:animated];
13 self.scrollView.contentSize = self.imageView.image.size;
14 self.imageView.frame = CGRectMake(0, 0, self.imageView.image.size.width, self.imageView.image.size.height);
15 }
16
17 @end
另外,附上我的一个小实验:
1 #import "ImaginariumViewController.h"
2
3 @interface ImaginariumViewController ()
4 @property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
5 @property (weak, nonatomic) IBOutlet UIImageView *imageView;
6 @end
7
8 @implementation ImaginariumViewController
9
10 - (void)viewDidLoad
11 {
12 [super viewDidLoad];
13 NSLog(@"viewDidLoad %g %g",self.scrollView.contentSize.width, self.scrollView.contentSize.height);
14 self.scrollView.contentSize = self.imageView.image.size;
15 }
16
17 - (void)viewWillAppear:(BOOL)animated
18 {
19 [super viewWillAppear:animated];
20 NSLog(@"viewWillAppear %g %g",self.scrollView.contentSize.width, self.scrollView.contentSize.height);
21 self.scrollView.contentSize = self.imageView.image.size;
22 }
23
24 - (void)viewDidAppear:(BOOL)animated
25 {
26 [super viewDidAppear:animated];
27 NSLog(@"viewDidAppear %g %g",self.scrollView.contentSize.width, self.scrollView.contentSize.height);
28 self.scrollView.contentSize = self.imageView.image.size;
29 self.imageView.frame = CGRectMake(0, 0, self.imageView.image.size.width, self.imageView.image.size.height);
30 }
31
32 - (void)didReceiveMemoryWarning
33 {
34 [super didReceiveMemoryWarning];
35 // Dispose of any resources that can be recreated.
36 }
37
38 @end
实验结果,console输出:
实验分析:
可以看到我在viewDidLoad方法和viewWillAppear方法之后都设置了contentSize,
但是发现viewDidLoad里设置是有效的,在viewWillAppear一开始log的值正是我们设置的700 655,
而在viewWillAppear里设置contentSize之后,viewDidAppear又还原了contentSize为0 0,
所以我猜测viewDidAppear才是真正执行Autolayout的地方,因此我们要设置contentSize就在viewDidAppear方法调用[super viewDidAppear:animated]之后吧。
这个实验也算是对上面的第二种解决方案的解释吧!