如果你在一個 UINavigationController 裡放一個 UIViewController,而該控制器的「第一個子視圖」剛好是 UIScrollView,就會發現 ScrollView 裡的所有子視圖都往下偏移了一截。這在 iOS 7 上尤其明顯。
重現用的程式碼如下:
- (void)viewDidLoad {
[super viewDidLoad];
UIScrollView *tempScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, 320, 200)];
[tempScroll setBackgroundColor:[UIColor grayColor]];
[tempScroll setContentSize:CGSizeMake(self.view.bounds.size.width, self.view.bounds.size.height)];
[self.view addSubview:tempScroll];
UIButton *tempButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[tempButton setBackgroundColor:[UIColor redColor]];
[tempButton setTitle:@"subView A" forState:UIControlStateNormal];
[tempButton setFrame:CGRectMake(80, 0, 80, 100)];
NSLog(@"%d", tempScroll.subviews.count);
[tempScroll addSubview:tempButton];
}經過驗證,我發現 iOS 7 存在這樣一個機制:在同時顯示 navigationBar 與 statusBar 的情況下,若某個 VC 的視圖子樹中「根部的第一個子視圖」是 ScrollView,那麼這個 ScrollView 的所有子視圖都會被下移 64 像素。
找到成因後,修正方案有兩個。
UIView *targetView = self.view;
while (targetView.subviews.count > 0 && ![targetView isKindOfClass:[UIScrollView class]]) {
targetView = [targetView.subviews objectAtIndex:0];
}
if ([targetView isKindOfClass:[UIScrollView class]]) {
NSLog(@"you are a scrollview");
CGSize tempSize = ((UIScrollView *)targetView).contentSize;
tempSize.height -= 64;
[(UIScrollView *)targetView setContentSize:tempSize];
for (UIView *subView in targetView.subviews) {
CGRect tempRect = subView.frame;
tempRect.origin.y -= 64;
[subView setFrame:tempRect];
}
}- (void)viewDidLoad {
[super viewDidLoad];
// 先墊一個背景視圖,讓 ScrollView 不再是「第一個子視圖」
UIView *tempBackGround = [[UIView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:tempBackGround];
UIScrollView *tempScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, 320, 200)];
[tempScroll setBackgroundColor:[UIColor grayColor]];
[tempScroll setContentSize:CGSizeMake(self.view.bounds.size.width, self.view.bounds.size.height)];
[self.view addSubview:tempScroll];
UIButton *tempButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[tempButton setBackgroundColor:[UIColor redColor]];
[tempButton setTitle:@"subView A" forState:UIControlStateNormal];
[tempButton setFrame:CGRectMake(80, 0, 80, 100)];
NSLog(@"%d", tempScroll.subviews.count);
[tempScroll addSubview:tempButton];
}修正後即可正常顯示。
