UIPickView & UIDatePickView

1.UIPickView(适用于本地添加数据)

项目中经常会需要自定义pickView;如下效果图

点击接送范围后弹出自定义的pickView

封装的代码如下:(底部放的是一张View)

图片所在控制器中调用的代码:

2.UIDatePickView

选择出发时间弹出自定义的UIDatePickView(底部放一张view)

3.支持“网络+本地”数据选择 CDZPicker

效果图

封装的.h文件

#import <UIKit/UIKit.h>

//NS_ASSUME_NONNULL_BEGIN

typedef void (^CDZCancelBlock)(void);
typedef void (^CDZConfirmBlock)(NSArray<NSString *> *strings, NSArray<NSNumber *> *indexs);

@interface CDZPickerComponentObject : NSObject

@property (nonatomic, strong, nullable) NSMutableArray<CDZPickerComponentObject *> *subArray;
@property (nonatomic, copy) NSString *text;

- (instancetype)initWithText:(NSString *)text subArray:(NSMutableArray *)array;
- (instancetype)initWithText:(NSString *)text;
@end


@interface CDZPickerBuilder : NSObject
//是否显示背后遮罩,默认为YES
@property (nonatomic, assign, getter=isShowMask) BOOL showMask;
//确认按钮的文字,默认为“确认”
@property (nonatomic, copy, nullable) NSString *confirmText;
//取消按钮的文字,默认为“取消”
@property (nonatomic, copy, nullable) NSString *cancelText;
//确认文字的颜色,默认是蓝色
@property (nonatomic, strong, nullable) UIColor *confirmTextColor;
//取消文字的颜色,默认为蓝色
@property (nonatomic, strong, nullable) UIColor *cancelTextColor;
//选择器的背景颜色,默认为白色
@property (nonatomic, strong, nullable) UIColor *pickerColor;
//选择器的文字颜色,默认为黑色
@property (nonatomic, strong, nullable) UIColor *pickerTextColor;
//默认滚动的行数,默认为第1行
@property (nonatomic, assign) NSInteger defaultIndex;
//整个pickerView的高度,默认为248,包括44的按钮栏
@property (nonatomic, assign) CGFloat pickerHeight;
@end

@interface CDZPicker : UIView

/**
 单行数据
 
 @param view 所在view
 @param builder 配置
 @param strings 单个string数组
 @param confirmBlock 点击确认后
 @param cancelBlcok 点击取消后
 */

+ (void)showSinglePickerInView:(UIView *)view
                   withBuilder:(nullable CDZPickerBuilder *)builder
                       strings:(NSArray<NSString *> *)strings
                       confirm:(CDZConfirmBlock)confirmBlock
                        cancel:(CDZCancelBlock)cancelBlcok;



/**
 多行不联动数据
 
 @param view 所在view
 @param builder 配置
 @param arrays 二维数组,数组里string数组个数为行数,互相独立
 @param confirmBlock 点击确认后
 @param cancelBlcok 点击取消后
 */

+ (void)showMultiPickerInView:(UIView *)view
                  withBuilder:(nullable CDZPickerBuilder *)builder
                 stringArrays:(NSArray<NSArray <NSString*> *> *)arrays
                      confirm:(CDZConfirmBlock)confirmBlock
                       cancel:(CDZCancelBlock)cancelBlcok;

/**
 多行联动数据
 
 @param view 所在的view
 @param builder 配置
 @param components 传入componetobject数组,可嵌套
 @param confirmBlock 点击确认后
 @param cancelBlcok 点击取消后
 */
+ (void)showLinkagePickerInView:(UIView *)view
                    withBuilder:(nullable CDZPickerBuilder *)builder
                     components:(NSArray<CDZPickerComponentObject *> *)components
                        confirm:(CDZConfirmBlock)confirmBlock
                         cancel:(CDZCancelBlock)cancelBlcok;

@end

//NS_ASSUME_NONNULL_END

封装的.m文件

#import "CDZPicker.h"

#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)
#define BACKGROUND_BLACK_COLOR [UIColor colorWithRed:0.412 green:0.412 blue:0.412 alpha:0.7]
static const NSInteger CDZPickerViewDefaultHeight = 248;
static const NSInteger CDZToolBarHeight = 44;

@implementation CDZPickerComponentObject
- (instancetype)init{
    return [self initWithText:@"" subArray:[NSMutableArray array]];
}

- (instancetype)initWithText:(NSString *)text{
    return [self initWithText:text subArray:[NSMutableArray array]];
}


- (instancetype)initWithText:(NSString *)text subArray:(NSMutableArray *)array{
    if (self = [super init]) {
        _text = text;
        _subArray = array;
    }
    return self;
}

@end

@implementation CDZPickerBuilder

- (instancetype)init{
    if (self = [super init]) {
        _showMask = YES;
        _defaultIndex = 0;
        _pickerHeight = CDZPickerViewDefaultHeight;
    }
    return self;
}
@end


@interface CDZPicker()<UIPickerViewDelegate,UIPickerViewDataSource>
@property (nonatomic, assign, getter=isLinkage) BOOL linkage;
@property (nonatomic, assign) NSInteger numberOfComponents;
@property (nonatomic, strong) CDZPickerBuilder *builder;
@property (nonatomic, copy) NSArray<CDZPickerComponentObject *> *componets;
@property (nonatomic, copy) CDZConfirmBlock confirmBlock;
@property (nonatomic, copy) CDZCancelBlock cancelBlock;
@property (nonatomic, copy) NSArray<NSArray <NSString*> *> *stringArrays;
@property (nonatomic, strong) NSMutableArray<NSMutableArray <CDZPickerComponentObject *> *> *rows;
@property (nonatomic, strong) UIPickerView *pickerView;
@property (nonatomic, strong) UIButton *confirmButton;
@property (nonatomic, strong) UIButton *cancelButton;
@property (nonatomic, strong) UIView *containerView;

@end

@implementation CDZPicker

#pragma mark - setup

- (void)config{
    if (!self.isLinkage) {
        self.numberOfComponents = self.stringArrays.count;
    }
    else{
        self.rows = [NSMutableArray array];
        CDZPickerComponentObject *object = self.componets.firstObject;
        [self.rows setObject:[NSMutableArray arrayWithArray:self.componets] atIndexedSubscript:0];
        for (self.numberOfComponents = 1;; self.numberOfComponents++) {
            [self.rows setObject:object.subArray atIndexedSubscript:self.numberOfComponents];
            object = [self objectAtIndex:0 inObject:object];
            if (!object) {
                break;
            }
        }
    }
    [self setupViews];
}


+ (void)showSinglePickerInView:(UIView *)view
                   withBuilder:(CDZPickerBuilder *)builder
                       strings:(NSArray<NSString *> *)strings
                       confirm:(CDZConfirmBlock)confirmBlock
                        cancel:(CDZCancelBlock)cancelBlcok{
    CDZPicker *pickerView = [[CDZPicker alloc]initWithFrame:view.frame];
    
    NSMutableArray *tmp = [NSMutableArray arrayWithCapacity:strings.count];
    for (NSString *string in strings) {
        CDZPickerComponentObject *object = [[CDZPickerComponentObject alloc]initWithText:string];
        [tmp addObject:object];
    }
    pickerView.linkage = YES;
    pickerView.componets = [tmp copy];
    pickerView.confirmBlock = confirmBlock;
    pickerView.cancelBlock = cancelBlcok;
    pickerView.builder = builder ?:[CDZPickerBuilder new];
    [pickerView config];
    [view addSubview:pickerView];
}

+ (void)showMultiPickerInView:(UIView *)view
                  withBuilder:(CDZPickerBuilder *)builder
                 stringArrays:(NSArray<NSArray<NSString *> *> *)arrays
                      confirm:(CDZConfirmBlock)confirmBlock cancel:(CDZCancelBlock)cancelBlcok{
    CDZPicker *pickerView = [[CDZPicker alloc]initWithFrame:view.frame];
    pickerView.linkage = NO;
    pickerView.stringArrays = arrays;
    pickerView.confirmBlock = confirmBlock;
    pickerView.cancelBlock = cancelBlcok;
    pickerView.builder = builder ?:[CDZPickerBuilder new];
    [pickerView config];
    [view addSubview:pickerView];
}


+ (void)showLinkagePickerInView:(UIView *)view
                    withBuilder:(CDZPickerBuilder *)builder
                     components:(NSArray<CDZPickerComponentObject *> *)components
                        confirm:(CDZConfirmBlock)confirmBlock
                         cancel:(CDZCancelBlock)cancelBlcok{
    CDZPicker *pickerView = [[CDZPicker alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    pickerView.linkage = YES;
    pickerView.componets = components;
    pickerView.confirmBlock = confirmBlock;
    pickerView.cancelBlock = cancelBlcok;
    pickerView.builder = builder ?:[CDZPickerBuilder new];
    [pickerView config];
    [view addSubview:pickerView];
}

- (void)setupViews{
    self.backgroundColor = self.builder.isShowMask ? BACKGROUND_BLACK_COLOR : UIColor.clearColor;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dissView)];
    [self addGestureRecognizer:tap];
    [self addSubview:self.containerView];
    
    [self.containerView addSubview:self.pickerView];
    [self.containerView addSubview:self.confirmButton];
    [self.containerView addSubview:self.cancelButton];
    NSInteger defaultIndex =  (self.builder.defaultIndex < self.numberOfComponents && self.builder.defaultIndex > 0) ? self.builder.defaultIndex : 0;
    [self.pickerView selectRow:defaultIndex inComponent:0 animated:NO];
}


#pragma mark - event response

- (void)confirm:(UIButton *)button{
    if (self.confirmBlock){
        NSMutableArray<NSString *> *resultStrings = [NSMutableArray arrayWithCapacity:self.numberOfComponents];
        NSMutableArray<NSNumber *> *resultIndexs = [NSMutableArray arrayWithCapacity:self.numberOfComponents];
        if ([self configResultStrings:resultStrings indexs:resultIndexs]) {
            self.confirmBlock([resultStrings copy],[resultIndexs copy]);
        }
    }
    [self removeFromSuperview];
}

- (void)dissView{
    if (self.cancelBlock) {
        self.cancelBlock();
    }
    [self removeFromSuperview];
}

- (void)cancel:(UIButton *)button{
    [self dissView];
}


#pragma mark - private

- (BOOL)configResultStrings:(NSMutableArray <NSString *> *)strings indexs:(NSMutableArray <NSNumber *> *)indexs{
    if (!strings || !indexs) {
        return NO;
    }
    
    [strings removeAllObjects];
    [indexs removeAllObjects];
    
    if (!self.isLinkage) {
        for (NSInteger index = 0; index < self.numberOfComponents; index++) {
            NSInteger indexRow = [self.pickerView selectedRowInComponent:index];
            [indexs addObject:@(indexRow)];
            NSArray<NSString *> *tmp = self.stringArrays[index];
            if (tmp.count > 0) {
                [strings addObject:tmp[indexRow]];
            }
        }
    }
    else{
        for (NSInteger index = 0; index < self.numberOfComponents; index++) {
            NSInteger indexRow = [self.pickerView selectedRowInComponent:index];
            [indexs addObject:@(indexRow)];
            NSMutableArray<CDZPickerComponentObject *> *tmp = self.rows[index];
            if (tmp.count > 0) {
                [strings addObject:tmp[indexRow].text];
            }
        }
    }
    return YES;
}

- (CDZPickerComponentObject *)objectAtIndex:(NSInteger)index inObject:(CDZPickerComponentObject *)object{
    if (object.subArray.count > index) {
        return object.subArray[index];
    }
    return nil;
}


#pragma mark - PickerDataSource

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return self.numberOfComponents;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (!self.isLinkage) {
        return self.stringArrays[component].count;
    }
    else{
        return self.rows[component].count;
    }
}



#pragma mark - PickerDelegate
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    return 44;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    if (!self.isLinkage) {
        return;
    }
    
    if (component < (self.numberOfComponents - 1)) {
        NSMutableArray<CDZPickerComponentObject *> *tmp = self.rows[component];
        if (tmp.count > 0) {
            tmp = tmp[row].subArray;
        }
        [self.rows setObject:((tmp.count > 0) ? tmp : [NSMutableArray array])  atIndexedSubscript:component + 1];
        
        [self pickerView:pickerView didSelectRow:0 inComponent:component + 1];
        [pickerView selectRow:0 inComponent:component + 1 animated:NO];
    }
    [pickerView reloadComponent:component];
}


- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    //设置分割线的颜色
    for(UIView *singleLine in pickerView.subviews){
        if (singleLine.frame.size.height < 1){
            singleLine.backgroundColor = UIColor.clearColor;
        }
    }
    //设置文字的属性
    UILabel *genderLabel = [UILabel new];
    genderLabel.textAlignment = NSTextAlignmentCenter;
    genderLabel.font = [UIFont systemFontOfSize:23.0];
    genderLabel.textColor = self.builder.pickerTextColor ?: UIColor.blackColor;
    
    if (!self.isLinkage) {
        NSArray<NSString *> *tmp = self.stringArrays[component];
        if (tmp.count > 0) {
            genderLabel.text = tmp[row];
        }
    }
    else{
        NSArray<CDZPickerComponentObject *> *tmp = self.rows[component];
        if (tmp.count > 0) {
            genderLabel.text = tmp[row].text;
        }
    }
    return genderLabel;
}



#pragma mark - getter

- (UIView *)containerView{
    if (!_containerView) {
        CGFloat pickerViewHeight = self.builder.pickerHeight > CDZToolBarHeight ? self.builder.pickerHeight : CDZPickerViewDefaultHeight;
        _containerView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT - pickerViewHeight, SCREEN_WIDTH, pickerViewHeight)];
        _containerView.backgroundColor = self.builder.pickerColor ?: UIColor.whiteColor;
    }
    return _containerView;
}



- (UIButton *)confirmButton{
    if (!_confirmButton) {
        _confirmButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH -70, 10, 40, 30)];
        _confirmButton.backgroundColor = UIColor.clearColor;
        _confirmButton.titleLabel.font = [UIFont systemFontOfSize:18.0];
        NSString *title = self.builder.confirmText.length ? self.builder.confirmText : @"确定";
        [_confirmButton setTitle:title forState:UIControlStateNormal];
        UIColor *color = self.builder.confirmTextColor ?: UToColor.redColor;
        [_confirmButton setTitleColor:color forState:UIControlStateNormal];
        [_confirmButton addTarget:self action:@selector(confirm:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _confirmButton;
}


- (UIButton *)cancelButton{
    if (!_cancelButton) {
        _cancelButton = [[UIButton alloc] initWithFrame:CGRectMake(30, 10, 40, 30)];
        _cancelButton.backgroundColor = UIColor.clearColor;
        _cancelButton.titleLabel.font = [UIFont systemFontOfSize:18.0];
        NSString *title = self.builder.cancelText.length ? self.builder.cancelText : @"取消";
        [_cancelButton setTitle:title forState:UIControlStateNormal];
        UIColor *color = self.builder.cancelTextColor ?: UToColor.redColor;
        [_cancelButton setTitleColor:color forState:UIControlStateNormal];
        [_cancelButton addTarget:self action:@selector(cancel:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelButton;
}


- (UIPickerView *)pickerView{
    if (!_pickerView) {
        CGFloat pickerViewHeight = self.builder.pickerHeight > CDZToolBarHeight ? self.builder.pickerHeight : CDZPickerViewDefaultHeight;
        _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0,CDZToolBarHeight, SCREEN_WIDTH, pickerViewHeight - CDZToolBarHeight)];
        _pickerView.backgroundColor = UIColor.clearColor;
        _pickerView.delegate = self;
        _pickerView.dataSource = self;
    }
    return _pickerView;
}
@end

调用地方示例:

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

推荐阅读更多精彩内容