我在程序開發時發現,將UINavigationController+UIScrollView組合起來使用時,我將UIImageView放入UIScrollView時,UIImageView並不是按照我預想的那樣,以UIScrollView的頂點作爲視圖添加的位置,這是由於UINavigationController在添加了導航欄以後,將會以導航欄下方作爲UIScrollView的原點位置,有時候我們想完全顯示該視圖的內容,解決方法,看下面這個程序
#import "RootViewController.h" @interface RootViewController () @property (retain,nonatomic,readwrite)UIScrollView * scrollView; @end @implementation RootViewController #define HIGHTOFNVBAR 64 #define HIGHTOFTOOLBAR 44 - (instancetype)init { self = [super init]; if (self) { } return self; } - (void)viewDidLoad { [super viewDidLoad]; [self.navigationController setNavigationBarHidden:NO animated:NO]; [self.navigationController setToolbarHidden:NO animated:NO]; self.view.backgroundColor = [UIColor blackColor]; _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)]; _scrollView.contentSize = CGSizeMake(960, 0); _scrollView.backgroundColor = [UIColor redColor]; [self.view addSubview:_scrollView]; UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)]; [_scrollView addGestureRecognizer:tapGesture]; _scrollView.pagingEnabled = YES; _scrollView.userInteractionEnabled = YES; _scrollView.showsHorizontalScrollIndicator = NO; _scrollView.showsVerticalScrollIndicator = NO; UIImageView *imageView1 = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)]; UIImageView *imageView2 = [[UIImageView alloc]initWithFrame:CGRectMake(320, 0, 320, 480)]; UIImageView *imageView3 = [[UIImageView alloc]initWithFrame:CGRectMake(640, 0, 320, 480)]; imageView1.image = [UIImage imageNamed:@"IMG_0242.JPG"]; imageView2.image = [UIImage imageNamed:@"IMG_0243.JPG"]; imageView3.image = [UIImage imageNamed:@"IMG_0244.JPG"]; _scrollView.contentInset = UIEdgeInsetsMake(-HIGHTOFNVBAR, 0, 0, 0); self.navigationController.toolbar.translucent = YES; self.navigationController.navigationBar.translucent = YES; _scrollView.delegate = self; NSLog(@"%@",NSStringFromCGRect(imageView2.frame)); [_scrollView addSubview:imageView1]; [_scrollView addSubview:imageView2]; [_scrollView addSubview:imageView3]; } - (void)tap:(UITapGestureRecognizer *)tap { static int i = 0; if (i%2 == 0) { [self.navigationController setNavigationBarHidden:YES animated:YES]; [self.navigationController setToolbarHidden:YES animated:YES]; _scrollView.contentInset = UIEdgeInsetsMake(0, 0, HIGHTOFTOOLBAR, 0); } else { [self.navigationController setNavigationBarHidden:NO animated:YES]; [self.navigationController setToolbarHidden:NO animated:YES]; _scrollView.contentInset = UIEdgeInsetsMake(0, 0, -HIGHTOFTOOLBAR, 0); } i++; }
使用UIScrollerView的contentInset屬性對UIScrollerView進行擴展即可