今天作了一個ScrollView的小例子(個人環境Xcode5.0.2 IOS7),結果發現沒法滾動,即便設置了scrollView的contentSize仍是不行,因而研究了一番,最終找到了解決方案:ios
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
另外,附上個人一個小實驗:atom
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輸出:spa
實驗分析:code
能夠看到我在viewDidLoad方法和viewWillAppear方法以後都設置了contentSize,blog
可是發現viewDidLoad裏設置是有效的,在viewWillAppear一開始log的值正是咱們設置的700 655,io
而在viewWillAppear裏設置contentSize以後,viewDidAppear又還原了contentSize爲0 0,console
因此我猜想viewDidAppear纔是真正執行Autolayout的地方,所以咱們要設置contentSize就在viewDidAppear方法調用[super viewDidAppear:animated]以後吧。class
這個實驗也算是對上面的第二種解決方案的解釋吧!import