您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 7 的 UIScrollView 尺寸位移問題與修正

編輯:iOS 開發綜合

如果你在一個 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 像素。

找到成因後,修正方案有兩個。

方案一:把 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];
    }
}

方案二:改變 ScrollView 的地位,讓它不是子視圖樹的第一個子視圖

- (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];
}

修正後即可正常顯示。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved