Imitation Kwai top menu and sub controller linkage effect, lazy loading to achieve loading controller
1. Implement top bar
//Top navigation Title
-(WY_ScrollButtonView *)scrollButtonView
{
if (!_scrollButtonView)
{
_scrollButtonView = [[WY_ScrollButtonView alloc]init];
_scrollButtonView.buttonTitleArray = @[@"Popular", @"Recommend",@"Same city"];
// _scrollButtonView.tintColor = [MyTool colorWithString:@"37c945"];
_scrollButtonView.defaultcolor = [UIColor blackColor];
_scrollButtonView.isLengthContainTitle = YES;
_scrollButtonView.backgroundColor = [UIColor clearColor];
_scrollButtonView.delete = self;
}
return _scrollButtonView;
}
2. Implement top bar click agent
//Top navigation delegate
-(void)buttonSelectedIndex:(NSInteger)index
{
[self.scrollView setContentOffset:CGPointMake(self.view.frame.size.width * index, 0) animated:YES];
}
3. Define controller switch view
-(UIScrollView *)scrollView
{
if (!_scrollView)
{
_scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0,0, self.view.frame.size.width, self.view.frame.size.height - 49 - 64)];
_scrollView.bounces = NO;
_scrollView.showsVerticalScrollIndicator = NO;
_scrollView.showsHorizontalScrollIndicator = NO;
_scrollView.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:0.1];
_scrollView.contentSize = CGSizeMake(self.view.frame.size.width * 3, 0);
_scrollView.delegate = self;
_scrollView.pagingEnabled = YES;
[self.view addSubview:_scrollView];
}
return _scrollView;
}
4. Add sub controller
//Add child controller
-(void)addChildViewController
{
NSArray *array = @[@"ViewControllerChaild1",@"ViewControllerChaild2",@"ViewControllerChaild3"];
for (int i = 0; i < array.count; i++)
{
UIViewController *vc = [[NSClassFromString(array[i]) alloc]init];
[self addChildViewController:vc];
}
self.scrollView.contentSize = CGSizeMake(WY_SCREENWIDTH * array.count, 0);
[self scrollViewDidEndDecelerating:self.scrollView];
}
5. Realize linkage and lazy loading controller
//End of slide add view
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
CGFloat width = self.view.frame.size.width;
CGFloat height = self.scrollView.frame.size.height;
CGFloat offsetX = scrollView.contentOffset.x;
//Get index
NSInteger scrollIndex = offsetX / width;
[self.scrollButtonView ScrollButtonViewDidScrollToIndex:scrollIndex];
UIViewController *vc = self.childViewControllers[scrollIndex];
if ([vc isViewLoaded]) return;
CGRect rect = CGRectMake(offsetX, 0, width, height);
vc.view.frame = rect;
[vc.view setFrame:rect];
[self.scrollView addSubview:vc.view];
}
//Call the main controller view at the end of scrollview deceleration
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
[self scrollViewDidEndScrollingAnimation:scrollView];
}
6. Renderings
Simple linkage is realized. If you want to add or modify, you can directly add or modify the controller in the array. It has strong scalability