UIScrollView添加多个UIViewController,并进行左右滑动,相关代码如下:
@interface DiscoverHomeViewController ()<UIScrollViewDelegate>{ DiscoverHotViewController *_hotVc; DiscoverPageViewController *_discoverVc; } @property (strong,nonatomic) UIScrollView *scrollView; @end @implementation DiscoverHomeViewController - (void)viewDidLoad { [super viewDidLoad]; [self initUI]; } /* 初始化UI */ - (void) initUI{ _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, self.view.bounds.size.width,self.view.bounds.size.height - 64)]; _scrollView.bounces = NO; _scrollView.showsHorizontalScrollIndicator = NO; _scrollView.showsVerticalScrollIndicator = NO; _scrollView.pagingEnabled = YES; _scrollView.scrollEnabled = NO; _scrollView.contentOffset = CGPointMake(0, 0); _scrollView.contentSize = CGSizeMake(_scrollView.bounds.size.width * 2, _scrollView.bounds.size.height); _scrollView.delegate = self; _scrollView.backgroundColor = [UIColor yellowColor]; //热门页面 _hotVc = [StoryboardUtil getVCWithSbIden:@"Discover" identify:@"DiscoverHotViewController"]; [_hotVc.view setFrame:CGRectMake(0, 0, _scrollView.bounds.size.width, _scrollView.bounds.size.height)]; [_scrollView addSubview:_hotVc.view]; [self addChildViewController:_hotVc]; //发现页面 _discoverVc = [StoryboardUtil getVCWithSbIden:@"Discover" identify:@"DiscoverPageViewController"]; [_discoverVc.view setFrame:CGRectMake(_scrollView.bounds.size.width, 0, _scrollView.bounds.size.width, _scrollView.bounds.size.height)]; [_scrollView addSubview:_discoverVc.view]; [self addChildViewController:_discoverVc]; //添加scrollView [self.view addSubview:_scrollView]; } /* 热门 */ - (IBAction)btnHotAction:(id)sender { //设按钮颜色 [self.btnDiscover setTitleColor:ContentTextColor forState:UIControlStateNormal]; [self.btnHot setTitleColor:[ColorUtil colorFromHexRGB:@"#000000"] forState:UIControlStateNormal]; [_scrollView setContentOffset:CGPointMake(0, 0) animated:YES]; } /* 发现 */ - (IBAction)btnDiscoverAction:(id)sender { //设按钮颜色 [self.btnDiscover setTitleColor:[ColorUtil colorFromHexRGB:@"#000000"] forState:UIControlStateNormal]; [self.btnHot setTitleColor:ContentTextColor forState:UIControlStateNormal]; [_scrollView setContentOffset:CGPointMake(_scrollView.bounds.size.width, 0) animated:YES]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end