應(yīng)用開發(fā)過程會有如下需求:
在當(dāng)前頁面肴颊,展示不同的Controller轻猖,添加button或其他的控件來控制在不同Controller之間切換
image.png
簡易代碼實現(xiàn):
@implementation ViewController
{
FirstViewController *_first;
SecondViewController *_second;
UIScrollView *_scrollView;
UISegmentedControl *_segmentedControl;
}
- (void)viewDidLoad {
[super viewDidLoad];
// segment
_segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"FirstViewController", @"SecondViewController"]];
[_segmentedControl setFrame:CGRectMake(20, 35, self.view.frame.size.width-40, 35)];
[self.view addSubview:_segmentedControl];
_segmentedControl.selectedSegmentIndex = 0;
[_segmentedControl addTarget:self action:@selector(SegmentedControlAction:) forControlEvents:UIControlEventValueChanged];
// 分類控制器
_scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 100, self.view.frame.size.width, self.view.frame.size.height-100)];
_scrollView.delegate = self;
[self.view addSubview:_scrollView];
_scrollView.pagingEnabled = YES;
_scrollView.backgroundColor = [UIColor whiteColor];
_scrollView.showsVerticalScrollIndicator = NO;
_scrollView.showsHorizontalScrollIndicator = NO;
_scrollView.contentSize = CGSizeMake(self.view.frame.size.width*2, self.view.frame.size.height-100);
_first = [[FirstViewController alloc] init];
_first.delegate = self;
_first.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 100);
_second = [[SecondViewController alloc] init];
_second.view.frame = CGRectMake(self.view.frame.size.width, 0, self.view.frame.size.width, self.view.frame.size.height - 100);
[_scrollView addSubview:_first.view];
[self addChildViewController:_first];
[_first didMoveToParentViewController:self];
[_scrollView addSubview:_second.view];
[self addChildViewController:_second];
[_second didMoveToParentViewController:self];
}
- (void)SegmentedControlAction:(UISegmentedControl *)sender {
if (sender.selectedSegmentIndex == 0) {
_scrollView.contentOffset = CGPointMake(0, 0);
} else {
_scrollView.contentOffset = CGPointMake(self.view.frame.size.width, 0);
}
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
if (scrollView.contentOffset.x == 0) {
_segmentedControl.selectedSegmentIndex = 0;
}
if (scrollView.contentOffset.x == self.view.frame.size.width) {
_segmentedControl.selectedSegmentIndex = 1;
}
}
@end
呈現(xiàn)效果:
截圖.gif