#pragma mark - 监听
/**
* 点击了顶部的标题按钮
*/
- (void)titleClick:(XMGTitleButton *)titleButton
{
// 修改按钮状态
self.clickedTitleButton.selected = NO;
titleButton.selected = YES;
self.clickedTitleButton = titleButton;
// 移除底部下划线
[UIView animateWithDuration:0.25 animations:^{
self.titleUnderlineView.width = titleButton.titleLabel.width;
self.titleUnderlineView.centerX = titleButton.centerX;
}];
// 让scrollView滚动到对应的位置(不要去修改contentOffset的y值)
CGPoint offset = self.scrollView.contentOffset;
offset.x = titleButton.tag * self.scrollView.width;
[self.scrollView setContentOffset:offset animated:YES];
//不是人为拖拽scrollView导致滚动完毕,会调用scrollViewDidEndScrollingAnimation这个方法
}
#pragma mark - <UIScrollViewDelegate>
/**
* 滚动完毕就会调用(如果不是人为拖拽scrollView导致滚动完毕,才会调用这个方法)
*/
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
int index = scrollView.contentOffset.x / scrollView.width;
UIViewController *willShowChildVc = self.childViewControllers[index];
// 如果这个子控制器的view已经添加过了,就直接返回
if (willShowChildVc.isViewLoaded) return;
// 添加子控制器的view
willShowChildVc.view.frame = scrollView.bounds;
[scrollView addSubview:willShowChildVc.view];
}
/**
* 滚动完毕就会调用(如果是人为拖拽scrollView导致滚动完毕,才会调用这个方法)
*/
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
int index = scrollView.contentOffset.x / scrollView.width;
// 点击对应的按钮
[self titleClick:self.titleButtons[index]];
// 添加子控制器的view
[self scrollViewDidEndScrollingAnimation:scrollView];
}
网友评论