ZXWSegmentControl.m 16.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
//
//  ZXWSegmentControl.m
//  LoongsCity
//
//  Created by loongs_zxw on 2017/11/15.
//  Copyright © 2017年 xiaoxiong. All rights reserved.
//

#import "ZXWSegmentControl.h"
#import "ZXWKitConst.h"
#import "ZXWSegment.h"
#import "UIView+ViewController.h"

typedef NS_ENUM(NSInteger, ScrollCtrlViewScrollStatus) {
    // 当前状态向左移动
    scrollCtrlViewScrollStatusToLeft,
    // 当前状态向右移动
    scrollCtrlViewScrollStatusToRight,
    // 正在状态静止
    scrollCtrlViewScrollStatusStatic,
};

@interface ZXWSegmentControl () <UIScrollViewDelegate>

/**
 *  是否是滑动标题
 */
@property (assign, nonatomic) BOOL isScrollTitle;

/**
 *  标题栏滑动试图
 */
@property (strong, nonatomic) UIScrollView * segementScrollView;

/**
 *  控制器试图滑动试图
 */
@property (strong, nonatomic) UIScrollView * scrollCtrlView;

/**
 *  底部栏试图
 */
@property (strong, nonatomic) UIView * bottomView;

/**
 *  当前选中索引
 */
@property (assign, nonatomic) ZXWSegment * currentItem;

/**
 *  将要选中的Item
 */
@property (assign, nonatomic) ZXWSegment * nextItem;

/**
 *  滑动控制器视图(下面的ScrollView)滑动状态
 */
@property (assign, nonatomic) ScrollCtrlViewScrollStatus scrollCtrlViewScrollStatus;

/**
 *  选中进度(1:选中状态,0:正常状态)
 */
@property (assign, nonatomic) CGFloat currentSelectProgress;

@property (nonatomic,strong) CNLiveBaseViewController *superVC;

@end

@implementation ZXWSegmentControl

#pragma mark - Lifecycle
- (void)layoutSubviews {
    [super layoutSubviews];
    
    // 设置当前Item默认值
    self.currentItem = [self.segementScrollView viewWithTag:1995 + _current];
    
    // 必须要在这个方法中调用,因为在这里才可以知道响应者链的顺序
    [self.viewController.view addSubview:self.scrollCtrlView];
    
    // 创建默认的控制器试图
    [self addCtrlViewToScrollViewWithCtrlIndex:_current];
    
    // 设置默认选中的Item
    self.currentItem.selectProgress = 1;
    
    // 为标题设置属性
    if (self.titles.count != 0) {
        for (UIView * subview in self.segementScrollView.subviews) {
            if ([subview isKindOfClass:[ZXWSegment class]]) {
                ZXWSegment * segment = (ZXWSegment *)subview;
                segment.titleNormalColor = self.titleNormalColor;
                NSString *textColor = self.textColors[segment.tag - 1995];
                if (textColor&&![textColor isEqualToString:@""]) {
                    segment.titleSelectColor = [UIColor colorWithHexString:textColor];
                }else{
                segment.titleSelectColor = self.titleSelectColor;
                }
                segment.isTitleScale = self.isTitleScale;
            }
        }
    }
    // 设置底部条的宽度
//    self.bottomView.width = self.currentItem.width;//Item的宽度
    //固定Item的宽度
    self.bottomView.width = ZXWSegementViewBottomViewWidth;
    self.bottomView.centerX = self.currentItem.centerX;

    // 设置底部条x值
//    self.bottomView.left = 0;
    if (self.bottomView.subviews.count != 0) {
        UIImageView * imageView = [self.bottomView.subviews firstObject];
        imageView.left = (self.bottomView.width - imageView.width) / 2;
    }
    
}

/**
 *  初始化静止标题栏(不可左右拖动)
 */
- (instancetype)initStaticTitlesWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        //
        self.isScrollTitle = NO;
        [self initDefault];
        [self creatSegementScrollView];
    }
    return self;
}

/**
 *  初始化滑动标题栏(可以左右拖动)
 */
- (instancetype)initScrollTitlesWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        //
        self.isScrollTitle = YES;
        [self initDefault];
        [self creatSegementScrollView];
    }
    return self;
}

/**
 *  初始化滑动标题栏(可以左右拖动)
 */
- (instancetype)initScrollTitlesWithFrame:(CGRect)frame viewController:(CNLiveBaseViewController *)vc{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.isScrollTitle = YES;
        self.superVC =vc;
        
        [self initDefault];
        [self creatSegementScrollView];
    }
    return self;
}

- (void)initDefault {
    self.titleNormalColor = segementColor_title_color;
    self.titleSelectColor = segementColor_title_select_color;
}
/**
 *  创建标题栏
 */
- (void)creatSegementScrollView {
    self.segementScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.width, self.height)];
    // 隐藏滑动条
    self.segementScrollView.showsVerticalScrollIndicator = NO;
    self.segementScrollView.showsHorizontalScrollIndicator = NO;
    self.segementScrollView.scrollsToTop = NO;
    [self addSubview:self.segementScrollView];
}

/**
 *  创建滑动控制器试图
 */
- (void)creatScrollCtrlView {
    // 滑动控制器试图y值
    CGFloat scrollCtrlViewY = self.origin.y + self.height;
    // 创建滑动控制器试图
    self.scrollCtrlView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, scrollCtrlViewY, ZXWkScreen_width, ZXWkScreen_height - scrollCtrlViewY)];
    self.scrollCtrlView.contentSize = CGSizeMake(self.viewControllers.count * ZXWkScreen_width, 0);
    // 隐藏滑动条
    self.scrollCtrlView.showsVerticalScrollIndicator = NO;
    self.scrollCtrlView.showsHorizontalScrollIndicator = NO;
    self.scrollCtrlView.backgroundColor = [UIColor whiteColor];
    // 取消回弹效果
    self.scrollCtrlView.bounces = NO;
    self.scrollCtrlView.delegate = self;
    self.scrollCtrlView.pagingEnabled = YES;
    [self.superVC.view addSubview:self.scrollCtrlView];
}
- (void)setCurrent:(NSInteger)current{
    _current = current;
    
    for (UIView *view in self.segementScrollView.subviews) {
        if (view.tag == (current +1995)) {
            ZXWSegment *segment =(ZXWSegment *)view;
            
            [self addCtrlViewToScrollViewWithCtrlIndex:_current];
            [self itemAction:segment];
        }
    }
}
#pragma mark - Custom Accessors

- (void)setTitles:(NSArray *)titles {
    _titles = titles[0];
    _textColors = titles[1];
    // Item的宽度
    CGFloat itemW = 0.0;
    CGFloat itemX = 0.0;
    for (int i = 0; i < _titles.count; i ++) {
        // 判断是滑动还是静止标题栏
        if (self.isScrollTitle == YES) {
            // 滑动标题栏
            
            // 计算文本标签的Size
            CGSize labelSize = [self sizeWithText:_titles[i] font:segementTitleNormalFont maxSize:CGSizeMake(ZXWkScreen_width, self.height)];
            // 计算Item的宽度  Item的宽度 = 本标签的宽度 + 间距
            itemW = labelSize.width + ZXWSegementViewTitlePadding / 2;
            // 设置contentSize
            self.segementScrollView.contentSize = [self getContentSize];
            // 滑动标题栏Item的x值在后面进行计算
        } else {
            // 静止标题栏
            
            // Item的宽度
            itemW = ZXWkScreen_width / _titles.count;
            // Item的x值
            itemX = i * itemW;
            // 设置contentSize
            self.segementScrollView.contentSize = CGSizeMake(ZXWkScreen_width, 0);
        }
        ZXWSegment * segment = [[ZXWSegment alloc] initWithFrame:CGRectMake(itemX, 0, itemW, self.height)];
        segment.title = _titles[i];
        segment.titleNormalColor = self.titleNormalColor;
        NSString *textColor = _textColors[i];
        if (textColor&&![textColor isEqualToString:@""]) {
            segment.titleSelectColor = [UIColor colorWithHexString:textColor];
        }else{
        segment.titleSelectColor = self.titleSelectColor;
        }
        segment.titleSelectBold = YES;
        segment.tag = 1995 + i;
        [segment addTarget:self action:@selector(itemAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.segementScrollView addSubview:segment];
        
        // 计算滑动标题栏Item的x值
        itemX += itemW;
    }
}

- (void)setViewControllers:(NSArray *)viewControllers {
    _viewControllers = viewControllers;
    [self creatScrollCtrlView];
}

#pragma mark - IBActions(事件)

/**
 *  标题项点击事件
 */
- (void)itemAction:(ZXWSegment *)segment {

    // 设置滑动试图的偏移量
    [self.scrollCtrlView setContentOffset:CGPointMake(ZXWkScreen_width * (segment.tag - 1995), 0) animated:NO];
    
    // 赋值
    self.currentItem = segment;
    
    [self setSegementAnimate];
}

#pragma mark - Public

/**
 *  设置底部栏颜色(和底部栏图片只能设置一个)
 */
- (void)setBottomViewColor:(UIColor *)color {
    self.bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, self.height - ZXWSegementViewBottomViewHeight, 0, ZXWSegementViewBottomViewHeight)];
    self.bottomView.backgroundColor = color;
    self.bottomView.layer.masksToBounds = YES;
    self.bottomView.layer.cornerRadius = 1.0;
    [self.segementScrollView addSubview:self.bottomView];
}

/**
 *  设置底部栏图片(和底部栏颜色只能设置一个)
 */
- (void)setBottomViewImage:(UIImage *)image {
    
    self.bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, self.height - 10, 0, 10)];
    [self.segementScrollView addSubview:self.bottomView];
    // 设置图片
    UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 15, 10)];
    imageView.image = image;
    [self.bottomView addSubview:imageView];
}

/**
 *  取消底部栏
 */
- (void)cancelBottomView {
    self.bottomView = nil;
}

#pragma mark - Private

/**
 *  添加控制器的视图到滑动试图上
 */
- (void)addCtrlViewToScrollViewWithCtrlIndex:(NSInteger)ctrlIndex {
    // 创建试图控制器
    UIViewController * VC = self.viewControllers[ctrlIndex];
    // 判断试图有没有加载过
    if ([VC isViewLoaded]) {
        return;
    }
    // 设置子视图
    VC.view.frame = CGRectMake(ctrlIndex * ZXWkScreen_width, 0, ZXWkScreen_width, ZXWkScreen_height - self.origin.y);

    [self.scrollCtrlView addSubview:VC.view];
    
    if (self.viewController) {
        [self.viewController addChildViewController:VC];
    }else {
        [self.superVC addChildViewController:VC];
    }
}

/**
 *  获取ContentSize
 */
- (CGSize)getContentSize {
    NSString * titleString = @"";
    for (NSString * title in self.titles) {
        titleString = [titleString stringByAppendingString:title];
    }
    // 计算总字符串得宽度
    CGSize stringWidth = [self sizeWithText:titleString font:segementTitleNormalFont maxSize:CGSizeMake(MAXFLOAT, self.height)];
    // 加上间距
    CGFloat totalWidth = stringWidth.width + self.titles.count * (ZXWSegementViewTitlePadding / 2);
    
    return CGSizeMake(totalWidth, 0);
}

/**
 *  计算文字尺寸
 *
 *  @param text    需要计算尺寸的文字
 *  @param font    文字的字体
 *  @param maxSize 文字的最大尺寸
 */
- (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font maxSize:(CGSize)maxSize
{
    NSDictionary *attrs = @{NSFontAttributeName : font};
    return [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}


/**
 *  修改选中进度
 */
- (void)changeSelectProgressWithCurrentIndex:(NSInteger)currentIndex {
    // 计算出当前选择的Item
    CGFloat selectIndex = self.scrollCtrlView.contentOffset.x / ZXWkScreen_width;
    // 计算出变化跨度是几
    CGFloat changeIndexNumber = selectIndex - currentIndex;
    // 取绝对值,向上取整操作
    changeIndexNumber = ceil(fabs(changeIndexNumber));
    // 获取将要选中的Item
    if (self.scrollCtrlViewScrollStatus == scrollCtrlViewScrollStatusToLeft) {
        // 试图向左拖拽
        self.nextItem = [self.segementScrollView viewWithTag:self.currentItem.tag + changeIndexNumber];
    } else if (self.scrollCtrlViewScrollStatus == scrollCtrlViewScrollStatusToRight) {
        // 试图向右拖拽
        self.nextItem = [self.segementScrollView viewWithTag:self.currentItem.tag - changeIndexNumber];
    }
    [UIView animateWithDuration:0.3 animations:^{
        // 设置将要选中Item的选择进度
        self.nextItem.selectProgress = 1 - self.currentSelectProgress;
        self.currentItem.selectProgress = self.currentSelectProgress;
        // 设置底部栏视图
        // 两个标题项中宽度的差
        CGFloat differenceW = self.nextItem.width - self.currentItem.width;
        // 设置动画增长或缩短宽度
//        self.bottomView.width = self.currentItem.width + (differenceW * (1 - self.currentSelectProgress));
        // 两个标题项中x的差
        CGFloat differenceX = self.nextItem.left - self.currentItem.left;
        // 设置动画修改x值
//        self.bottomView.left = self.currentItem.left + (differenceX * (1 - self.currentSelectProgress));
        self.bottomView.centerX = self.nextItem.centerX;

        // 判断底部条是否是图片,如果是图片设置图片
        if (self.bottomView.subviews.count != 0) {
            UIImageView * imageView = [self.bottomView.subviews firstObject];
            imageView.left = (self.bottomView.width - imageView.width) / 2;
        }
        
    }];
}

/**
 *  设置标题栏动画
 */
- (void)setSegementAnimate {
    
    if (_segementScrollView.contentSize.width < MainScreenWidth) {
        return;
    }
    // 当前选中的Item
    ZXWSegment * currentItem = self.currentItem;
    // 标题栏动画
    [UIView animateWithDuration:0.3 animations:^{
        // 判断能否设置居中(除开距离不够的)
        if (currentItem.center.x > (self.width / 2) && currentItem.center.x < (self.segementScrollView.contentSize.width - self.width / 2)) {
            // 居中的偏移量 = 标题按钮的偏移量 - 屏幕宽度的一半
            CGFloat contentOffsetX = currentItem.center.x - (ZXWkScreen_width / 2);
            self.segementScrollView.contentOffset = CGPointMake(contentOffsetX, 0);
        } else if (currentItem.center.x < self.width / 2) {
            self.segementScrollView.contentOffset = CGPointMake(0, 0);
        } else if (currentItem.center.x > (self.segementScrollView.contentSize.width - self.width / 2)) {
            self.segementScrollView.contentOffset = CGPointMake(self.segementScrollView.contentSize.width - (self.width), 0);
        }
    }];
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    NSInteger currentIndex = self.currentItem.tag - 1995;
    if (scrollView.contentOffset.x > (currentIndex * ZXWkScreen_width)) {
        // 向左滑动,偏移量变大
        self.currentSelectProgress = 1 - (fmod (scrollView.contentOffset.x, ZXWkScreen_width) / ZXWkScreen_width);
        // 设置手势是向左滑动
        self.scrollCtrlViewScrollStatus = scrollCtrlViewScrollStatusToLeft;
        // 保持从0 -> 1,也就是从非选中到选中状态
        if (self.currentSelectProgress == 0) {
            self.currentSelectProgress = 1;
        } else if (self.currentSelectProgress == 1) {
            self.currentSelectProgress = 0;
        }
    } else if (scrollView.contentOffset.x < (currentIndex * ZXWkScreen_width)) {
        // 向右滑动,偏移量变小
        self.currentSelectProgress = fmod (scrollView.contentOffset.x, ZXWkScreen_width) / ZXWkScreen_width;
        // 设置手势是向右滑动
        self.scrollCtrlViewScrollStatus = scrollCtrlViewScrollStatusToRight;
    }
    // 修改选中进度
    [self changeSelectProgressWithCurrentIndex:currentIndex];
    
    // 判断选中进度(其实不判断也可以,判断就不会一直调用节省性能)
    if (self.currentSelectProgress > 0.95 || self.currentSelectProgress == 0.0) {
        // 添加控制器试图到滑动试图上
        [self addCtrlViewToScrollViewWithCtrlIndex:self.nextItem.tag - 1995];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSInteger currentIndex = scrollView.contentOffset.x / ZXWkScreen_width;
    self.currentItem = [self.segementScrollView viewWithTag:currentIndex + 1995];
    scrollView.scrollEnabled = YES;
    [self setSegementAnimate];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    scrollView.scrollEnabled = NO;
    
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    scrollView.scrollEnabled = YES;
    [self setSegementAnimate];
}


@end