iOS开发 - 滚动选择器

简介: iOS开发 - 滚动选择器

因为在项目中有用到滚动选择滑块切换控制器的控件,之前都是用的别人封装好的,但在使用中总感觉不舒服,对方的库写的也比较乱,所以博主一直想封装一个属于自己的滑动选择器,先看下效果图:


仔细察看的话会发现点击到中间位置时会有个小问题,会反方向滚动一段距离,该问题已修复,直接下载Demo查看即可

image.png

下面放下代码:

//
//  ScrollSliderView.h
//  滚动导航条页面
//
//  Created by XXX on 16/6/13.
//  Copyright © 2016年 CodingFire. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ScrollSliderView : UIView<UIScrollViewDelegate>
#define VIEWWIDTH [UIScreen mainScreen].bounds.size.width
#define VIEWHEIGHT [UIScreen mainScreen].bounds.size.height
#define RAN_COLOR(CUS_RGB) [UIColor colorWithRed:((float)((CUS_RGB & 0xFF0000) >> 16))/255.0 green:((float)((CUS_RGB & 0xFF00) >> 8))/255.0 blue:((float)(CUS_RGB & 0xFF))/255.0 alpha:1.0f]
/*
 *
 *初始化数据
 */
-(id)initWithController:(UIViewController *)controller withTitleArray:(NSArray *)titleArray;
/*
 *底部ScrollView
 */
@property (nonatomic,strong)UIScrollView *mainScrollView;
/*
 *滑块ScrollView
 */
@property (nonatomic,strong)UIScrollView *sliderScrollView;
/*
 *存放title的数组
 */
@property (nonatomic,copy)NSArray *dataArray;
/*
 *点击或滑动后选中的位置
 */
@property (nonatomic, assign) NSInteger selectIndex;
/*
 *所在的控制器
 */
@property (nonatomic,weak)UIViewController *fatherController;
@end
//
//  ScrollSliderView.m
//  滚动导航条页面
//
//  Created by XXX on 16/6/13.
//  Copyright © 2016年 CodingFire. All rights reserved.
//
#import "ScrollSliderView.h"
#import "SubViewController.h"
#import "Cache.h"
@implementation ScrollSliderView
{
    Cache *cache;
}
/*
 *初始化底部ScrollView
 */
-(UIScrollView *)mainScrollView{
    if (!_mainScrollView) {
        _mainScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 100, VIEWWIDTH, VIEWHEIGHT-100)];
        _mainScrollView.bounces = NO;
        _mainScrollView.showsVerticalScrollIndicator = NO;
        _mainScrollView.showsHorizontalScrollIndicator = NO;
        _mainScrollView.pagingEnabled = YES;
        _mainScrollView.backgroundColor = [UIColor lightGrayColor];
        _mainScrollView.delegate = self;
    }
    return _mainScrollView;
}
/*
 *初始化self所有的控件
 */
-(id)initWithController:(UIViewController *)controller withTitleArray:(NSArray *)titleArray
{
    if (self = [super initWithFrame:[UIScreen mainScreen].bounds]) {
        cache = [[Cache alloc]init];
        _dataArray = [NSArray arrayWithArray:titleArray];
        _fatherController = controller;
        [self mainScrollView];
        [self addSubview:_mainScrollView];
        [self creatSliderScrollView:titleArray];
        _mainScrollView.contentSize = CGSizeMake(titleArray.count*VIEWWIDTH, VIEWHEIGHT - 64 - 36);
        SubViewController *subVC = [SubViewController new];
        subVC.index = 0;
        subVC.tilte = _dataArray[0];
        subVC.view.frame = CGRectMake(0,0, VIEWWIDTH,_mainScrollView.frame.size.height);
        subVC.view.backgroundColor = [UIColor colorWithHue:(arc4random() % 256 / 256.0) saturation:(arc4random() % 128 / 256.0) + 0.5 brightness:(arc4random() % 128) + 0.5 alpha:1];
        [_mainScrollView addSubview:subVC.view];
        [controller addChildViewController:subVC];
        [cache addCacheSelectIndex:0];
    }
    return self;
}
/*
 *创建滑块
 */
- (void)creatSliderScrollView:(NSArray *)array{
    _sliderScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0,64, VIEWWIDTH, 36)];
    _sliderScrollView.backgroundColor = [UIColor whiteColor];
    _sliderScrollView.bounces = NO;
    _sliderScrollView.showsHorizontalScrollIndicator = NO;
    _sliderScrollView.showsVerticalScrollIndicator = NO;
    [self addSubview:_sliderScrollView];
    CGFloat spaceWidth = 6;
    CGFloat widthContentSize = 0;
    for (NSInteger i = 0; i < array.count; i++) {
        NSString *titleName = self.dataArray[i];
        NSInteger strWidth = [self sizeforWidthWithString:titleName];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        UIView *sliderSign = [[UIView alloc]initWithFrame:CGRectMake(spaceWidth + widthContentSize,33,strWidth + 10,2)];
        sliderSign.backgroundColor = RAN_COLOR(0xE43494);
        sliderSign.tag = 10000 + i;
        btn.frame = CGRectMake(spaceWidth+widthContentSize,2,strWidth + 10,32);
        [btn setTitle:titleName forState:UIControlStateNormal];
        [btn setTitleColor:RAN_COLOR(0xE43494) forState:UIControlStateSelected];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_sliderScrollView addSubview:btn];
        [_sliderScrollView addSubview:sliderSign];
        btn.tag = 20000 + i;
        if (i == 0) {
            btn.selected = YES;
            sliderSign.hidden = NO;
        }else{
            sliderSign.hidden = YES;
        }
        widthContentSize = strWidth+10+spaceWidth+widthContentSize;
        [btn addTarget:self action:@selector(selectIndexTableViewAndCollectionView:) forControlEvents:UIControlEventTouchUpInside];
    }
    self.sliderScrollView.contentSize = CGSizeMake(widthContentSize + 6, 36);
}
/*
 *计算title的长度
 */
-(NSInteger)sizeforWidthWithString:(NSString *)str
{
    NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:14]};
    CGSize size = [str boundingRectWithSize:CGSizeMake(VIEWWIDTH - 10, 0) options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
    return size.width;
}
/*
 *点击滑块按钮响应事件
 */
- (void)selectIndexTableViewAndCollectionView:(UIButton *)sender{
    //按钮点击 先把所有的按钮都不选中 滑动条View隐藏
    for (NSInteger i = 0; i < _dataArray.count; i++) {
        UIButton *btn = (UIButton *)[self viewWithTag:20000 + i];
        UIView *sliderSign = (UIView *)[self viewWithTag:10000 + i];
        sliderSign.hidden = YES;
        btn.selected = NO;
    }
    NSInteger index = sender.tag - 20000;
    self.selectIndex = index;
    //选中 为选中状态
    sender.selected = YES;
    UIView *View = (UIView *)[self viewWithTag:index + 10000];
    View.hidden = NO;
    UIButton *btnRight = [_sliderScrollView viewWithTag:sender.tag + 1];
    UIButton *btnLeft = [_sliderScrollView viewWithTag:sender.tag - 1];
    //分页 显示哪个控制器
    _mainScrollView.contentOffset = CGPointMake(index*VIEWWIDTH,0);
    if ((sender.frame.origin.x + sender.frame.size.width) > VIEWWIDTH - 10){
        if (sender.tag != (20000 + _dataArray.count - 1)) {
            [UIView animateWithDuration:0.3f animations:^{
                self.sliderScrollView.contentOffset = CGPointMake(btnRight.frame.origin.x + btnRight.frame.size.width - VIEWWIDTH, 0);
            }];
        }
    }
    else
    {
        [UIView animateWithDuration:0.3f animations:^{
            self.sliderScrollView.contentOffset = CGPointMake(btnLeft.frame.origin.x, 0);
        }];
    }
    if (![cache hasCacheIndex:_selectIndex]) {
        [self addSubController];
    }
}
/*
 *创建未创建的滑块对应控制器
 */
-(void)addSubController
{
    SubViewController *subVC = [SubViewController new];
    subVC.index = _selectIndex;
    subVC.tilte = _dataArray[_selectIndex];
    [_mainScrollView addSubview:subVC.view];
    subVC.view.frame = CGRectMake(_selectIndex*VIEWWIDTH,0, VIEWWIDTH,_mainScrollView.frame.size.height);
    subVC.view.backgroundColor = [UIColor colorWithHue:(arc4random() % 256 / 256.0) saturation:(arc4random() % 128 / 256.0) + 0.5 brightness:(arc4random() % 128) + 0.5 alpha:1];
    [_mainScrollView addSubview:subVC.view];
    [_fatherController addChildViewController:subVC];
}
/*
 *UIScrollViewDelegate,控制滑动后变化
 */
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSInteger index = scrollView.contentOffset.x/VIEWWIDTH;
    _selectIndex = index;
    for (NSInteger i = 0; i < _dataArray.count; i++) {
        UIButton *btn = (UIButton *)[self viewWithTag:20000 + i];
        UIView *downSliderView = (UIView *)[self viewWithTag:10000 + i];
        if (index == i) {
            downSliderView.hidden = NO;
            btn.selected = YES;
        }else{
            downSliderView.hidden = YES;
            btn.selected = NO;
        }
    }
    UIButton *btnRight = [_sliderScrollView viewWithTag:index + 1 + 20000];
    UIButton *btnCenter = [_sliderScrollView viewWithTag:index + 20000];
    UIButton *btnLeft = [_sliderScrollView viewWithTag:index - 1 + 20000];
    //分页 显示哪个控制器
    _mainScrollView.contentOffset = CGPointMake(index * VIEWWIDTH,0);
    if ((btnCenter.frame.origin.x + btnCenter.frame.size.width) > VIEWWIDTH - 10){
        if (btnCenter.tag != (20000 + _dataArray.count - 1)) {
            [UIView animateWithDuration:0.3f animations:^{
                _sliderScrollView.contentOffset = CGPointMake(btnRight.frame.origin.x + btnRight.frame.size.width - VIEWWIDTH, 0);
            }];
        }
    }
    else
    {
        [UIView animateWithDuration:0.3f animations:^{
            _sliderScrollView.contentOffset = CGPointMake(btnLeft.frame.origin.x, 0);
        }];
    }
    if (![cache hasCacheIndex:_selectIndex]) {
        [self addSubController];
    }
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
@end

这里便是核心代码,另外还有个储存控制器的类,不再列出来了。这里博主写的比较传统,并没有进行高度的封装,很多属性没有单独留出来,也怪博主懒,也是给大家提供一个发挥的空间,如果有什么疑问和不合理的地方,欢迎留言,代码下载地址请看:https://github.com/codeliu6572/ScrollSelector

目录
相关文章
|
1月前
|
iOS开发 开发者
uniapp开发ios打包Error code = -5000 Error message: Error: certificate file(p12) import failed!报错问题如何解决
uniapp开发ios打包Error code = -5000 Error message: Error: certificate file(p12) import failed!报错问题如何解决
141 67
uniapp开发ios打包Error code = -5000 Error message: Error: certificate file(p12) import failed!报错问题如何解决
|
3月前
|
开发框架 前端开发 Android开发
安卓与iOS开发中的跨平台策略
在移动应用开发的战场上,安卓和iOS两大阵营各据一方。随着技术的演进,跨平台开发框架成为开发者的新宠,旨在实现一次编码、多平台部署的梦想。本文将探讨跨平台开发的优势与挑战,并分享实用的开发技巧,帮助开发者在安卓和iOS的世界中游刃有余。
|
2天前
|
JavaScript 搜索推荐 Android开发
【01】仿站技术之python技术,看完学会再也不用去购买收费工具了-用python扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-客户的麻将软件需要下载落地页并且要做搜索引擎推广-本文用python语言快速开发爬取落地页下载-优雅草卓伊凡
【01】仿站技术之python技术,看完学会再也不用去购买收费工具了-用python扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-客户的麻将软件需要下载落地页并且要做搜索引擎推广-本文用python语言快速开发爬取落地页下载-优雅草卓伊凡
22 8
【01】仿站技术之python技术,看完学会再也不用去购买收费工具了-用python扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-客户的麻将软件需要下载落地页并且要做搜索引擎推广-本文用python语言快速开发爬取落地页下载-优雅草卓伊凡
|
2月前
|
iOS开发 开发者 MacOS
深入探索iOS开发中的SwiftUI框架
【10月更文挑战第21天】 本文将带领读者深入了解Apple最新推出的SwiftUI框架,这一革命性的用户界面构建工具为iOS开发者提供了一种声明式、高效且直观的方式来创建复杂的用户界面。通过分析SwiftUI的核心概念、主要特性以及在实际项目中的应用示例,我们将展示如何利用SwiftUI简化UI代码,提高开发效率,并保持应用程序的高性能和响应性。无论你是iOS开发的新手还是有经验的开发者,本文都将为你提供宝贵的见解和实用的指导。
143 66
|
2月前
|
存储 监控 API
app开发之安卓Android+苹果ios打包所有权限对应解释列表【长期更新】-以及默认打包自动添加权限列表和简化后的基本打包权限列表以uniapp为例-优雅草央千澈
app开发之安卓Android+苹果ios打包所有权限对应解释列表【长期更新】-以及默认打包自动添加权限列表和简化后的基本打包权限列表以uniapp为例-优雅草央千澈
87 11
|
2月前
|
开发框架 Android开发 iOS开发
安卓与iOS开发中的跨平台策略:一次编码,多平台部署
在移动应用开发的广阔天地中,安卓和iOS两大阵营各占一方。随着技术的发展,跨平台开发框架应运而生,它们承诺着“一次编码,到处运行”的便捷。本文将深入探讨跨平台开发的现状、挑战以及未来趋势,同时通过代码示例揭示跨平台工具的实际运用。
173 3
|
2月前
|
Java 调度 Android开发
安卓与iOS开发中的线程管理差异解析
在移动应用开发的广阔天地中,安卓和iOS两大平台各自拥有独特的魅力。如同东西方文化的差异,它们在处理多线程任务时也展现出不同的哲学。本文将带你穿梭于这两个平台之间,比较它们在线程管理上的核心理念、实现方式及性能考量,助你成为跨平台的编程高手。
|
3月前
|
存储 前端开发 Swift
探索iOS开发:从新手到专家的旅程
本文将带您领略iOS开发的奇妙之旅,从基础概念的理解到高级技巧的掌握,逐步深入iOS的世界。文章不仅分享技术知识,还鼓励读者在编程之路上保持好奇心和创新精神,实现个人成长与技术突破。
|
3月前
|
安全 IDE Swift
探索iOS开发之旅:从初学者到专家
在这篇文章中,我们将一起踏上iOS开发的旅程,从基础概念的理解到深入掌握核心技术。无论你是编程新手还是希望提升技能的开发者,这里都有你需要的指南和启示。我们将通过实际案例和代码示例,展示如何构建一个功能齐全的iOS应用。准备好了吗?让我们一起开始吧!
|
3月前
|
安全 Swift iOS开发
Swift 与 UIKit 在 iOS 应用界面开发中的关键技术和实践方法
本文深入探讨了 Swift 与 UIKit 在 iOS 应用界面开发中的关键技术和实践方法。Swift 以其简洁、高效和类型安全的特点,结合 UIKit 丰富的组件和功能,为开发者提供了强大的工具。文章从 Swift 的语法优势、类型安全、编程模型以及与 UIKit 的集成,到 UIKit 的主要组件和功能,再到构建界面的实践技巧和实际案例分析,全面介绍了如何利用这些技术创建高质量的用户界面。
72 2

热门文章

最新文章