WMPageController使用总结

需求如下:


屏幕快照 2019-03-11 下午4.30.06.png

分页展示内容,可以通过手势滑动来切换点击,也可以使用点击title来切换页面,上下滑动的时候,我的订单会显示到导航栏中。

思路:
1、可以自己实现,写一个类集成UIScrollView,可以通过暴露以下方法来实现:

@interface TopSelectBar : UIScrollView
@property (nonatomic, copy) NSArray *titleArr;
@property (nonatomic, copy) void (^didSelectedAt)(NSInteger index);
@property (nonatomic, assign) NSInteger curIndex;
@property (nonatomic, assign) CGFloat itemWidth;
@property (nonatomic, strong) UIImageView *thumbView;
@property (nonatomic, assign) CGFloat thumbPos; //0~maxIndex
@property (nonatomic, strong) UIColor *thumbColor;
@property (nonatomic, assign) CGSize thumbSize;
@property (nonatomic, strong) UIColor *titleColor;
@property (nonatomic, strong) UIColor *titleSelColor;
@property (nonatomic, strong) UIView *bottomLine;

- (void)setTitle:(NSString*)title AtIndex:(NSInteger)index;

.m具体实现:

#define BaseTag     1024

@implementation TopSelectBar
{
    NSInteger _tolCount;
    NSArray *_items;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.showsHorizontalScrollIndicator = NO;
        self.showsVerticalScrollIndicator = NO;
        self.backgroundColor = [UIColor whiteColor];
        _thumbColor = [UIColor SCTextBlueColor];
        _titleColor = [UIColor whiteColor];
        _titleSelColor = [UIColor greenColor];
        _curIndex = 0;
        _thumbSize = CGSizeMake(60, 3);
        _itemWidth = 70;
    }
    return self;
}

- (void)setItemWidth:(CGFloat)itemWidth {
    _itemWidth = itemWidth;
    [self initSubViews];
}

- (void)setTitleArr:(NSArray *)titleArr {
    _titleArr = [titleArr copy];
    [self initSubViews];
}

- (void)setThumbColor:(UIColor *)thumbColor {
    _thumbColor = thumbColor;
    if (_thumbView)
        _thumbView.backgroundColor = thumbColor;
}

- (void)setThumbSize:(CGSize)thumbSize {
    _thumbSize = thumbSize;
    if (_thumbView) {
        _thumbView.size = thumbSize;
        _thumbView.top = self.height - _thumbSize.height;
    }
    [self updateThumbWithAnimate:NO];
}

- (void)setTitleColor:(UIColor *)titleColor {
    _titleColor = titleColor;
    for (NSInteger i = 0; i < _items.count; i++) {
        UIButton *button = _items[i];
        [button setTitleColor:titleColor forState:UIControlStateNormal];
    }
}

- (void)setTitleSelColor:(UIColor *)titleSelColor {
    _titleSelColor = titleSelColor;
    for (NSInteger i = 0; i < _items.count; i++) {
        UIButton *button = _items[i];
        [button setTitleColor:titleSelColor forState:UIControlStateSelected];
    }
}

- (void)initSubViews
{
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    _thumbView = nil;
    if (_titleArr.count <= 0)
        return;
    
    if (_items.count > 0) {
        [_items makeObjectsPerformSelector:@selector(removeFromSuperview)];
        _items = nil;
    }
    
//  self.contentMode = UIViewContentModeCenter;
    self.contentSize = CGSizeMake(_titleArr.count * _itemWidth, CGRectGetHeight(self.frame));
    NSMutableArray *temp = [[NSMutableArray alloc] init];
    for (int i = 0; i < _titleArr.count; i++)
    {
        NSString *title = [_titleArr objectAtIndex:i];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = BaseTag + i;
        [button setTitle:title forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        [button setTitleColor:_titleColor forState:UIControlStateNormal];
        [button setTitleColor:_titleSelColor forState:UIControlStateSelected];
        button.frame = CGRectMake(_itemWidth * i, 0, _itemWidth, self.bounds.size.height);
        button.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        [button addTarget:self action:@selector(tapAction:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];
        [temp addObject:button];
    }
    _items = temp;
    
    _bottomLine = [[UIView alloc] initWithFrame:CGRectMake(-150, self.height - .5, self.contentSize.width + 300, .5)];
    _bottomLine.backgroundColor = [UIColor whiteColor];
    [self addSubview:_bottomLine];
    
    if (!_thumbView) {
        _thumbView = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.height - _thumbSize.height, _thumbSize.width, _thumbSize.height)];
        _thumbView.backgroundColor = _thumbColor;
        [self addSubview:_thumbView];
    }
    [self updateThumbWithAnimate:NO];
}

- (void)updateThumbWithAnimate:(BOOL)animate
{
    CGFloat centerX = _curIndex * _itemWidth + _itemWidth / 2;
    if (animate)
    {
        [UIView animateWithDuration:0.2 animations:^{
            _thumbView.centerX = centerX;
        }];
    }
    else
        _thumbView.centerX = centerX;
}

- (void)setTitle:(NSString*)title AtIndex:(NSInteger)index
{
    if (index < 0 || index > _items.count - 1)
        return;
    
    UIButton *button = [_items objectAtIndex:index];
    [button setTitle:title forState:UIControlStateNormal];
}

- (void)setThumbPos:(CGFloat)thumbPos {
    
    _thumbView.centerX = _itemWidth * thumbPos + _itemWidth / 2;
    
    if (_thumbPos<=thumbPos) {
        if (self.contentOffset.x>_itemWidth*_thumbPos) {
            CGPoint po = CGPointMake(_itemWidth*_thumbPos, 0);
            self.contentOffset = po;
        }else {
            if (self.contentOffset.x+kSCREEN_WIDTH<_itemWidth*_thumbPos+_itemWidth) {
                CGPoint po = CGPointMake(_itemWidth*(_thumbPos+1)-kSCREEN_WIDTH, 0);
                self.contentOffset = po;
            }
        }
    }else {
        if (kSCREEN_WIDTH<_itemWidth*_thumbPos-self.contentOffset.x) {
            CGPoint po = CGPointMake(_itemWidth*(_thumbPos+1)-kSCREEN_WIDTH, 0);
            self.contentOffset = po;
        }else {
            if (self.contentOffset.x>_itemWidth*_thumbPos) {
                CGFloat hh;
                if (self.contentOffset.x-_itemWidth<0) {
                    hh = 0;
                }else {
                    hh = _itemWidth*(_thumbPos);
                }
                CGPoint po = CGPointMake(hh, 0);
                self.contentOffset = po;
                
            }
        }
        
    }
    
    _thumbPos = thumbPos;
    NSInteger index = roundf(thumbPos);
    if (index != _curIndex) {
        UIButton *oldSelBtn = _items[_curIndex];
        oldSelBtn.selected = NO;
        UIButton *selBtn = _items[index];
        selBtn.selected = YES;
        _curIndex = index;
    }
}

- (void)updateScrollRect:(UIView*)view {
    CGFloat offset = 0;
    if ((view.left - self.contentOffset.x) < 0)
        offset = view.left - self.contentOffset.x;
    else if ((view.right - self.width) > 0)
        offset = view.right - self.width;

    if (offset != 0)
        [self scrollRectToVisible:CGRectMake(self.contentOffset.x + offset, 0, self.width, self.height) animated:YES];
}

- (void)setCurIndex:(NSInteger)curIndex {
    UIButton *oldSelBtn = _items[_curIndex];
    oldSelBtn.selected = NO;
    UIButton *selBtn = _items[curIndex];
    selBtn.selected = YES;
    _curIndex = curIndex;
    [self updateThumbWithAnimate:YES];
    [self updateScrollRect:selBtn];
    if (_didSelectedAt)
        _didSelectedAt(_curIndex);
}

- (void)tapAction:(id)sender
{
    UIButton *button = (UIButton*)sender;
    self.curIndex = button.tag - BaseTag;
}

具体使用如下:

- (TopSelectBar*)topBar {
    if (!_topBar) {
        _topBar = [[TopSelectBar alloc] initWithFrame:CGRectMake(0, 1, kSCREEN_WIDTH, 46)];
        _topBar.backgroundColor = [UIColor whiteColor];
        _topBar.itemWidth = kSCREEN_WIDTH/2;
        _topBar.titleArr = @[@"基本信息",@"更多信息"];
        _topBar.titleColor = [UIColor SCTextLightGrayColor];
        _topBar.titleSelColor = [UIColor SCBlackColor];
        _topBar.thumbSize = CGSizeMake(42, 3);
        _topBar.thumbColor =[UIColor SCLightBlueColor];
        @Weakify(self);
        _topBar.didSelectedAt = ^(NSInteger index){
            @Strongify(self);
            if (index == 0) {
                self.headView.hidden = NO;
                self.mTableView.hidden = YES;
            }else{
                self.headView.hidden = YES;
                self.mTableView.hidden = NO;
            }
        };
        
    }
    return _topBar;
}

2、可以直接使用第三方分页菜单控制器WMPageController.

作用

1)这是一个类似于UINavigationController 和 UITabBarController 的一个UIViewController 的一个管理类。
2)用来分页展示内容的,可以通过手势滑动来切换页面,也可以使用点击title来切换页面 是一个用来管理ViewController的一个类,将 它的subViewController设置为每一个ViewController ,然后将这些subViewController 放在ScrollView 上面,故称呼为一个ViewController 的一个管理类。

如何使用

1、由于该第三方库支持CocoaPods。在项目中直接pod即可。
github地址:WMPageController

platform :ios,'9.0'

target 'DemoTest1' do

 pod 'WMPageController', '~> 1.6.4'

end

2、自定义一个ArtScrollView继承自UIScrollView,重写代理方法。

//返回YES,则可以多个手势一起触发方法,返回NO则为互斥(比如外层UIScrollView名为mainScroll内嵌的UIScrollView名为subScroll,当我们拖动subScroll时,mainScroll是不会响应手势的(多个手势默认是互斥的),当下面这个代理返回YES时,subScroll和mainScroll就能同时响应手势,同时滚动,这符合我们这里的需求)
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

该ArtScrollView用在MainViewController中,解决UIScrollView嵌套的手势冲突问题。

3、创建一个控制器作为容器

@interface SQHoverPageViewController ()<UIScrollViewDelegate,WMPageControllerDelegate>
@property (nonatomic, strong) WMPageController *pageController;
@property (nonatomic, strong) ArtScrollView *containerScrollView;
@property (nonatomic, strong) UIView *bannerView;
@property (nonatomic, strong) UILabel *titleLb;
@property (nonatomic, strong) UILabel *navTitleLb;
@property (nonatomic, strong) UIView *contentView;

/*view*/

/*model*/

@property (nonatomic, assign) BOOL isTopIsCanNotMoveTabView;
@property (nonatomic, assign) BOOL isTopIsCanNotMoveTabViewPre;
@property (nonatomic, assign) BOOL scrollViewCanScroll;   // 最底部的scrollView是否能滚动的标志
@property (nonatomic,copy) NSArray *childViewControllerClasses;
@property (nonatomic,copy) NSArray *childViewControllertitles;
@property (nonatomic,copy) NSArray *sids;
@property (nonatomic,copy) NSString *naviTitle;
@property (nonatomic,strong) NSMutableArray *last2OffsetY;
@property (nonatomic,assign) NSInteger index;
@end
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"标题";
    _canScroll = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(acceptMsg:) name:kHomeLeaveTopNotification object:nil];
    [self setupView];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.navigationController.navigationBar.alpha = 0;
}

- (void)setupView {
    [self.view addSubview:self.containerScrollView];
    [self.containerScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.bottom.trailing.equalTo(self.view).offset(0);
    }];
    [self.containerScrollView addSubview:self.bannerView];
    [self.bannerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.trailing.equalTo(self.containerScrollView);
        make.width.equalTo(self.containerScrollView);
        make.height.mas_equalTo(200);
    }];
    [self.containerScrollView addSubview:self.contentView];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.bannerView.mas_bottom);
        make.leading.trailing.bottom.equalTo(self.containerScrollView);
        make.width.equalTo(self.containerScrollView);
        make.height.mas_equalTo(kScreenHeight-64);
    }];
    [self.contentView addSubview:self.pageController.view];
    self.pageController.viewFrame = CGRectMake(0, 0, kScreenWidth, kScreenHeight-64);
}

#pragma mark - getter

- (ArtScrollView *)containerScrollView {
    if (!_containerScrollView) {
        _containerScrollView = [[ArtScrollView alloc] init];
        _containerScrollView.delegate = self;
        _containerScrollView.showsVerticalScrollIndicator = NO;
    }
    return _containerScrollView;
}

- (UIView *)bannerView {
    if (!_bannerView) {
        _bannerView = [[UIView alloc] init];
        _bannerView.backgroundColor = [UIColor blueColor];
    }
    return _bannerView;
}

- (UIView *)contentView {
    if (!_contentView) {
        _contentView = [[UIView alloc] init];
        _contentView.backgroundColor = [UIColor yellowColor];
    }
    return _contentView;
}

- (WMPageController *)pageController {
    if (!_pageController) {
        _pageController = [[WMPageController alloc] initWithViewControllerClasses:@[[ChildTableViewController class],[ChildTableViewController class],[ChildTableViewController class]] andTheirTitles:@[@"tab1",@"tab2",@"tab3"]];
        _pageController.menuViewStyle      = WMMenuViewStyleLine;
        _pageController.menuHeight         = 44;
        _pageController.progressWidth      = 20;
        _pageController.titleSizeNormal    = 15;
        _pageController.titleSizeSelected  = 15;
        _pageController.titleColorNormal   = [UIColor grayColor];
        _pageController.titleColorSelected = [UIColor blueColor];
    }
    return _pageController;
}

#pragma mark - notification

-(void)acceptMsg:(NSNotification *)notification{
    NSDictionary *userInfo = notification.userInfo;
    NSString *canScroll = userInfo[@"canScroll"];
    if ([canScroll isEqualToString:@"1"]) {
        _canScroll = YES;
    }
}

#pragma mark - UIScrollViewDelegate

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    CGFloat maxOffsetY = 136;
    CGFloat offsetY = scrollView.contentOffset.y;
    self.navigationController.navigationBar.alpha = offsetY/136;
    if (offsetY>=maxOffsetY) {
        scrollView.contentOffset = CGPointMake(0, maxOffsetY);
        //NSLog(@"滑动到顶端");
        [[NSNotificationCenter defaultCenter] postNotificationName:kHomeGoTopNotification object:nil userInfo:@{@"canScroll":@"1"}];
        _canScroll = NO;
    }else{
        //NSLog(@"离开顶端");
        if (!_canScroll) {
            scrollView.contentOffset = CGPointMake(0, maxOffsetY);
        }
    }
}

// 移除通知
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

3、为WMPageController创建子控制器。

#import "ChildTableViewController.h"

@interface ChildTableViewController ()<UIScrollViewDelegate>
@property (nonatomic, assign) BOOL canScroll;
@end

@implementation ChildTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cellid"];
    // add notification
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(acceptMsg:) name:kHomeGoTopNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(acceptMsg:) name:kHomeLeaveTopNotification object:nil];//其中一个TAB离开顶部的时候,如果其他几个偏移量不为0的时候,要把他们都置为0
}

#pragma mark - notification

-(void)acceptMsg:(NSNotification *)notification{
    NSString *notificationName = notification.name;
    if ([notificationName isEqualToString:kHomeGoTopNotification]) {
        NSDictionary *userInfo = notification.userInfo;
        NSString *canScroll = userInfo[@"canScroll"];
        if ([canScroll isEqualToString:@"1"]) {
            self.canScroll = YES;
            self.tableView.showsVerticalScrollIndicator = YES;
        }
    }else if([notificationName isEqualToString:kHomeLeaveTopNotification]){
        self.tableView.contentOffset = CGPointZero;
        self.canScroll = NO;
        self.tableView.showsVerticalScrollIndicator = NO;
    }
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (!self.canScroll) {
        [scrollView setContentOffset:CGPointZero];
    }
    CGFloat offsetY = scrollView.contentOffset.y;
    if (offsetY<0) {
        [[NSNotificationCenter defaultCenter] postNotificationName:kHomeLeaveTopNotification object:nil userInfo:@{@"canScroll":@"1"}];
    }
}


#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 20;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellid" forIndexPath:indexPath];
    cell.textLabel.text = [NSString stringWithFormat:@"第%ld行",indexPath.row];
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

// 移除通知
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,530评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 86,403评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,120评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,770评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,758评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,649评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,021评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,675评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,931评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,659评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,751评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,410评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,004评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,969评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,042评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,493评论 2 343

推荐阅读更多精彩内容