實(shí)際項(xiàng)目中我們可能經(jīng)常遇到一個(gè)界面有很多的子視圖,就如今日頭條的那樣, 因此在下在這里簡單的寫了一個(gè) demo 來解決, 并附上github 地址https://github.com/wyxlh/WKTitleScorll
- 1,導(dǎo)入頭文件 并定義 并實(shí)現(xiàn) UIScrollViewDelegate協(xié)議 還需要一些宏定義,具體的看
//獲取設(shè)備的物理高度
#define ScreenHeight [UIScreen mainScreen].bounds.size.height
//獲取設(shè)備的物理寬度
#define ScreenWidth [UIScreen mainScreen].bounds.size.width
#define WS(weakSelf) __weak __typeof(&*self)weakSelf = self;
#define SKOrangeColor [UIColor colorWithRed:250/255. green:50/255. blue:100/255. alpha:1]
#import "TitleScrollView.h"
#import "UIView+Frame.h"
@property (nonatomic,strong)TitleScrollView *titleScroll;
- 2 實(shí)現(xiàn)
- (TitleScrollView *)titleScroll
{
if (!_titleScroll)
{
WS(weakSelf)
_titleScroll = [[TitleScrollView alloc] initWithFrame:CGRectMake(0,64, ScreenWidth, 47) TitleArray:self.titleArr selectedIndex:0 scrollEnable:NO lineEqualWidth:YES isLarger:YES selectColor:SKOrangeColor defaultColor:[UIColor blackColor] SelectBlock:^(NSInteger index) {
[weakSelf titleClick:index];
}];
_titleScroll.backgroundColor = [UIColor whiteColor];
[self.view addSubview:_titleScroll];
}
return _titleScroll;
}
- 3添加子視圖 并 實(shí)現(xiàn)對應(yīng)的協(xié)議
#pragma mark 底部的scrollview
-(void)setupContentView {
//不要自動調(diào)整inset
self.automaticallyAdjustsScrollViewInsets = NO;
UIScrollView *contentView = [[UIScrollView alloc] init];
contentView.frame = CGRectMake(0, self.titleScroll.height, ScreenWidth, ScreenHeight);
contentView.delegate = self;
contentView.contentSize = CGSizeMake(contentView.width * self.childViewControllers.count, 0);
contentView.pagingEnabled = YES;
[self.view insertSubview:contentView atIndex:0];
self.contentView = contentView;
self.contentView.contentOffset = CGPointMake(0*ScreenWidth, 0);
//添加第一個(gè)控制器的view
[self scrollViewDidEndScrollingAnimation:contentView];
}
#pragma mark 便簽欄按鈕點(diǎn)擊
-(void)titleClick:(NSInteger)index {
//滾動,切換子控制器
CGPoint offset = self.contentView.contentOffset;
offset.x = index * self.contentView.width;
[self.contentView setContentOffset:offset animated:YES];
}
#pragma mark -UIScrollViewDelegate
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
//添加子控制器的view
//當(dāng)前索引
NSInteger index = scrollView.contentOffset.x / scrollView.width;
//取出子控制器
UIViewController *vc = self.childViewControllers[index];
vc.view.x = scrollView.contentOffset.x;
vc.view.y = 0;//設(shè)置控制器的y值為0(默認(rèn)為20)
vc.view.height = scrollView.height;//設(shè)置控制器的view的height值為整個(gè)屏幕的高度(默認(rèn)是比屏幕少20)
[scrollView addSubview:vc.view];
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
[self scrollViewDidEndScrollingAnimation:scrollView];
//當(dāng)前索引
NSInteger index = scrollView.contentOffset.x / scrollView.width;
//點(diǎn)擊butto
[self.titleScroll setSelectedIndex:index];
}
-(void)addChildViewControllers{
for (int i = 0; i < self.titleArr.count; i++) {
WKChildViewController *child = [[WKChildViewController alloc]init];
child.index = i;
[self addChildViewController:child];
}
}