iOS-自定义PickerView

分享一个自定义的日期选择控件,或者其他自定义选择项,通过UIPickerView实现,实现Pickerview的几个代理方法,设置数据计算等操作。

其中引用自定义的几个类,可以自己相应的做些调整。

实现的功能:
日期选择的时候:可以设置年,月,日,时,分,秒其中的任意组合显示。可以设置可选过去和未来的时间,或者只能选择过去时间,或者只能选择未来的时间,可以设置pickerview自定义的顶部和底部视图,可以设置。
自定义选择模式:比如一些简单的数量什么选择都可以。

调用一句话

+ (void)showPickerDateWithConfigBlock:(void(^)(YHPickerViewController * pickerVC))pickerSettingBlock andPickerFinish:(void(^)(id selectItems))pickerFinishBlock;

在block中设置配置的信息

YHPickerViewController.h

//
//  YHPickerViewController.h
//  TallyBook
//
//  Created by 林宁宁 on 16/9/11.
//  Copyright © 2016年 林宁宁. All rights reserved.
//

#import "BaseViewController.h"

@class YHDatePickerItem;
@class YHPickerItem;

/**
 *  时间日期选择模式
 */
typedef NS_ENUM(NSInteger, PickerDateType) {
    
    /**
     *  自定义选择 要去设置  block
     */
    PickerDateType_Block           = -1,
    
    /**
     *  自定义选择 要去设置  dataList
     */
    PickerDateType_Custom           = 0,
    
    /**
     *  年
     */
    PickerDateType_Year             = 1 << 0,
    
    /**
     *  月
     */
    PickerDateType_Month            = 1 << 1,
    
    /**
     *  日
     */
    PickerDateType_Day              = 1 << 2,
    
    /**
     *  时
     */
    PickerDateType_Hour             = 1 << 3,
        
    /**
     *  分
     */
    PickerDateType_Minute           = 1 << 4,
    
    /**
     *  秒
     */
    PickerDateType_Second           = 1 << 5
    
};


typedef NS_ENUM(NSInteger, PickerDateSelectAble)
{
    /** 过去未来都可选*/
    PickerDateSelectAble_all,
    
    /** 只能选未来的时间*/
    PickerDateSelectAble_future,
    
    /** 只能选过去的时间*/
    PickerDateSelectAble_old
};




@interface YHPickerViewController : BaseViewController



/*******************  时间选择模式  *******************/

/** 时间选择的模式 */
@property (assign, nonatomic) PickerDateType pickerMode;

/** 初始定位的日期 */
@property (retain, nonatomic) NSDate * dateOrigin;

/** 可选时间的类型 过去-未来-无限制*/
@property (assign, nonatomic) PickerDateSelectAble picker_able;

/** 选中的是什么 年月日时分*/
@property (retain, nonatomic, readonly) YHDatePickerItem * pickerDateSelect;



/*******************  自定义block模式  *******************/

/** 组件的数量*/
@property (copy, nonatomic) NSInteger(^pickerComponentCountBlock)();

/** 组件中row的number*/
@property (copy, nonatomic) NSInteger(^pickerRowCountBlock)(NSInteger component);

/** 某块显示的数据*/
@property (copy, nonatomic) NSString *(^pickerTitleRowBlock)(NSInteger component,NSInteger row);

/** 选中某块数据*/
@property (copy, nonatomic) void(^pickerSelectRowBlock)(NSInteger component,NSInteger row);

/** 选中的下标*/
@property (retain, nonatomic) NSDictionary * pickerSelectIndexDicBlock;

/*******************  自定义选择模式  *******************/


/** 这个里面的数据是 YHPickerItem 类型  自定义类型的时候*/
@property (retain, nonatomic) NSArray<YHPickerItem *> * dataList;




/************************* 通用 ****************************/


/**
 *  选择器的标题
 */
@property (copy, nonatomic) NSString * pickerTitle;

/** 点击完成之后  YHPickerItem 类型*/
@property (strong, nonatomic) void(^pickerFinishBlock)(id selectItems);

/**
 *  自定义底部视图
 */
@property (retain, nonatomic) UIView * customBottmV;
/**
 *  默认 30
 */
@property (assign, nonatomic) float customBottmVHeight;
/**
 *  自定义顶部视图
 */
@property (retain, nonatomic) UIView * customTopV;
/**
 *  默认 30
 */
@property (assign, nonatomic) float customTopVHeight;



- (void)selectRow:(NSInteger)row inComponent:(NSInteger)component;




+ (void)showPickerDateWithConfigBlock:(void(^)(YHPickerViewController * pickerVC))pickerSettingBlock andPickerFinish:(void(^)(id selectItems))pickerFinishBlock;


@end










@interface YHDatePickerItem : NSObject

@property (nonatomic, assign) NSInteger currentYear;
@property (nonatomic, assign) NSInteger currentMonth;
@property (nonatomic, assign) NSInteger currentDay;
@property (nonatomic, assign) NSInteger currentHour;
@property (nonatomic, assign) NSInteger currentMinute;
@property (nonatomic, assign) NSInteger currentSecond;

@property (nonatomic, assign) NSInteger yearMin;
@property (nonatomic, assign) NSInteger yearMax;

@property (nonatomic, assign) NSInteger year;
@property (nonatomic, assign) NSInteger month;
@property (nonatomic, assign) NSInteger day;
@property (nonatomic, assign) NSInteger hour;
@property (nonatomic, assign) NSInteger minute;
@property (nonatomic, assign) NSInteger second;

@property (nonatomic, copy) NSString * dateDescrption;

@end










@interface YHPickerItem : NSObject


//类型
@property (copy, nonatomic)     NSString * pickerTitle;
@property (retain, nonatomic)   NSArray <NSString *>* pickerDataList;
@property (copy, nonatomic)     NSString * pickerSelectTitle;

/**
 *  获取标题
 */
@property (copy, nonatomic) NSString *(^getPickerTitleBlock)(NSInteger index);

- (instancetype)initWithTitle:(NSString *)title andPickerList:(NSArray <NSString *>*)list andPickerSelectTitle:(NSString *)selectTitle;


@end


YHPickerViewController.m

//
//  YHPickerViewController.m
//  TallyBook
//
//  Created by 林宁宁 on 16/9/11.
//  Copyright © 2016年 林宁宁. All rights reserved.
//

#import "YHPickerViewController.h"
#import <Masonry.h>
#import "UIFont+BBX.h"
#import "UIColor+BBXApp.h"
#import "NSString+BBX.h"
#import "NSDate+BBX.h"
#import <YYKit/NSDate+YYAdd.h>





@interface YHPickerViewController()<UIPickerViewDelegate,UIPickerViewDataSource>

@property (retain, nonatomic) UIPickerView * datePicker;

@property (retain, nonatomic, readwrite) YHDatePickerItem * pickerDateSelect;

@property (retain, nonatomic) UIView * bgView;

@property (retain, nonatomic) UIView * toolV;

@property (assign, nonatomic) float component_width;


@end

@implementation YHPickerViewController

-(void)defaultConfigSetting
{
    self.view.backgroundColor = [UIColor clearColor];
    self.customTopVHeight = 30;
    self.customBottmVHeight = 30;
    
    self.pickerDateSelect = [YHDatePickerItem new];
    self.pickerDateSelect.currentHour = [NSDate date].hour;
    self.pickerDateSelect.currentYear = [NSDate date].year;
    self.pickerDateSelect.currentMonth = [NSDate date].month;
    self.pickerDateSelect.currentDay = [NSDate date].day;
    self.pickerDateSelect.currentMinute = [NSDate date].minute;
    self.pickerDateSelect.currentSecond = [NSDate date].second;
    self.pickerDateSelect.yearMin = 1900;
    self.pickerDateSelect.yearMax = self.pickerDateSelect.currentYear + 100;
    
    self.dateOrigin = [NSDate date];
}

-(void)setDateOrigin:(NSDate *)dateOrigin
{
    _dateOrigin = dateOrigin;
    
    self.pickerDateSelect.year = dateOrigin.year;
    self.pickerDateSelect.month = dateOrigin.month;
    self.pickerDateSelect.day = dateOrigin.day;
    self.pickerDateSelect.hour = dateOrigin.hour;
    self.pickerDateSelect.minute = dateOrigin.minute;
    self.pickerDateSelect.second = dateOrigin.second;
    self.pickerDateSelect.dateDescrption = [dateOrigin description];
}

- (void)showPickerView
{
    if(self.pickerMode == PickerDateType_Custom)
    {
        self.component_width = (CGRectGetWidth(self.view.frame)-(self.dataList.count-1)*5)/self.dataList.count;
    }
    else if (self.pickerMode == PickerDateType_Block)
    {
        self.component_width = (CGRectGetWidth(self.view.frame)-(self.pickerComponentCountBlock()-1)*5)/self.pickerComponentCountBlock();
        
        self.pickerSelectIndexDicBlock = [NSMutableDictionary new];
    }
    else
    {
        NSInteger count = [self typeShowComponentCount];
        self.component_width = CGRectGetWidth(self.view.frame)/count;
    }
    
    
    __weak typeof(&*self)weakSelf = self;
    
    UIView * bgView = [UIView new];
    self.bgView = bgView;
    bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.2];
    bgView.alpha = 0;
    [self.view addSubview:bgView];
    
    UITapGestureRecognizer * tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pickerNumCancel)];
    [bgView addGestureRecognizer:tapGes];
    
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf.view);
    }];
    
    if(self.customBottmV)
    {
        [self.view addSubview:self.customBottmV];
        [self.customBottmV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(weakSelf.view);
            make.height.mas_equalTo(weakSelf.customBottmVHeight);
        }];
    }
    
    self.datePicker = [[UIPickerView alloc] init];
    self.datePicker.delegate = self;
    self.datePicker.dataSource = self;
    self.datePicker.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.datePicker];
    
    
    [self.datePicker mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.view);
        if(weakSelf.customBottmV)
        {
            make.bottom.equalTo(weakSelf.customBottmV.mas_top).offset(300);
        }
        else
        {
            make.bottom.equalTo(weakSelf.view).offset(20).offset(300);
        }
        make.height.mas_equalTo(250);
    }];
    
    
    if(self.customTopV)
    {
        [self.view addSubview:self.customTopV];
        
        [self.customTopV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(weakSelf.view);
            make.bottom.equalTo(weakSelf.datePicker.mas_top).offset(20);
            make.height.mas_equalTo(weakSelf.customTopVHeight);
        }];
    }
    
    [self resetOriginAnimation];
    
    
    [self creatToolBar];
    
    [self.view layoutIfNeeded];
    
    [self.datePicker mas_updateConstraints:^(MASConstraintMaker *make) {
        if(weakSelf.customBottmV)
        {
            make.bottom.equalTo(weakSelf.customBottmV.mas_top);
        }
        else
        {
            make.bottom.equalTo(weakSelf.view).offset(20);
        }
    }];
    
    [UIView animateWithDuration:0.3 delay:0 usingSpringWithDamping:0.7 initialSpringVelocity:0.7 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        
        self.bgView.alpha = 1;
        
        [self.view layoutIfNeeded];
        
    } completion:^(BOOL finished) {
        
    }];
}


- (void)pickerNumCancel
{
    __weak typeof(&*self)weakSelf = self;
    [self.datePicker mas_updateConstraints:^(MASConstraintMaker *make) {
        if(weakSelf.customBottmV)
        {
            make.bottom.equalTo(weakSelf.customBottmV.mas_top).offset(300);
        }
        else
        {
            make.bottom.equalTo(weakSelf.view).offset(20).offset(300);
        }
    }];
    
    [UIView animateWithDuration:0.3 delay:0 usingSpringWithDamping:1 initialSpringVelocity:0.6 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        
        [self.view layoutIfNeeded];
        
    } completion:^(BOOL finished) {
        [self.view removeFromSuperview];
        [self removeFromParentViewController];
    }];
}

- (void)pickerNumSubmit
{
    if(self.pickerFinishBlock)
    {
        if(self.pickerMode == PickerDateType_Custom)
        {
            self.pickerFinishBlock(self.dataList);
        }
        else if (self.pickerMode == PickerDateType_Block)
        {
            self.pickerFinishBlock(self.pickerSelectIndexDicBlock);
        }
        else
        {
            self.pickerFinishBlock(self.pickerDateSelect.dateDescrption);
        }
    }
    
    [self pickerNumCancel];
}


#pragma mark - picker view的代理

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    if(self.pickerMode == PickerDateType_Custom)
    {
        return self.dataList.count;
    }
    else if (self.pickerMode == PickerDateType_Block)
    {
        return self.pickerComponentCountBlock();
    }
    
    return [self typeShowComponentCount];
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if(self.pickerMode == PickerDateType_Custom)
    {
        YHPickerItem * item = self.dataList[component];
        
        return item.pickerDataList.count;
    }
    else if (self.pickerMode == PickerDateType_Block)
    {
        return self.pickerRowCountBlock(component);
    }
    
    PickerDateType type = [self typeShowAtComponent:component];
    switch (type) {
        case PickerDateType_Year:
        {
            //年
            return self.pickerDateSelect.yearMax - self.pickerDateSelect.yearMin;
        }
            break;
        case PickerDateType_Month:
        {
            //月
            return 12;
        }
            break;
        case PickerDateType_Day:
        {
            //日
            return [self getDayCountAtSelectMonth];
        }
            break;
        case PickerDateType_Hour:
        {
            //时
            return 24;
        }
            break;
        case PickerDateType_Minute:
        {
            //分
            return 60;
        }
            break;
        case PickerDateType_Second:
        {
            //秒
            return 60;
        }
            break;
        default:
            
            break;
    }
    return 0;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    if(self.pickerMode == PickerDateType_Custom ||
       self.pickerMode == PickerDateType_Block)
    {
        return self.component_width;
    }
    
    PickerDateType type = [self typeShowAtComponent:component];
    if(type == PickerDateType_Year)
    {
        return self.component_width;
    }
    else
    {
        return self.component_width*0.65;
    }
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 45;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    NSString * titleStr = @"";
    float width_component = self.component_width;
    
    if(self.pickerMode == PickerDateType_Custom)
    {
        YHPickerItem * item = self.dataList[component];
        
        titleStr =  item.pickerDataList[row];
    }
    else if (self.pickerMode == PickerDateType_Block)
    {
        titleStr =  self.pickerTitleRowBlock(component,row);
    }
    else
    {
        PickerDateType type = [self typeShowAtComponent:component];
        switch (type) {
            case PickerDateType_Year:
            {
                //年
                titleStr = [NSString stringWithFormat:@"%d年",(int)(self.pickerDateSelect.yearMax - row)];
            }
                break;
            case PickerDateType_Month:
            {
                //月
                titleStr = [NSString stringWithFormat:@"%02d月",(int)row+1];
                width_component = self.component_width * 0.65;
            }
                break;
            case PickerDateType_Day:
            {
                //日
                titleStr = [NSString stringWithFormat:@"%02d日",(int)row+1];
                width_component = self.component_width * 0.65;
            }
                break;
            case PickerDateType_Hour:
            {
                //时
                titleStr = [NSString stringWithFormat:@"%02d时",(int)row+1];
                width_component = self.component_width * 0.65;
            }
                break;
            case PickerDateType_Minute:
            {
                //分
                titleStr = [NSString stringWithFormat:@"%02d分",(int)row+1];
                width_component = self.component_width * 0.65;
            }
                break;
            case PickerDateType_Second:
            {
                //秒
                titleStr = [NSString stringWithFormat:@"%02d秒",(int)row+1];
                width_component = self.component_width * 0.65;
            }
                break;
            default:
                
                break;
        }
    }
    
    
    
    UILabel * labTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width_component, 45)];
    
    labTitle.text = titleStr;
    labTitle.textAlignment = NSTextAlignmentCenter;
    labTitle.textColor = [UIColor flatBlackColor];
    labTitle.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    labTitle.font = [UIFont bbxSystemFont:17];
    labTitle.adjustsFontSizeToFitWidth = YES;
    
    if([titleStr containStr:@"\n"])
    {
        labTitle.numberOfLines = 0;
        labTitle.lineBreakMode = NSLineBreakByWordWrapping;
        labTitle.font = [UIFont bbxSystemFont:16];
        
        NSRange returnRange = [titleStr rangeOfString:@"\n"];
        
        NSMutableAttributedString * attStr = [[NSMutableAttributedString alloc] initWithString:titleStr];
        
        [attStr addAttributes:@{NSFontAttributeName:[UIFont bbxSystemFont:16]} range:NSMakeRange(0, returnRange.location)];
        [attStr addAttributes:@{NSFontAttributeName:[UIFont bbxSystemFont:8]} range:NSMakeRange(returnRange.location, returnRange.length)];
        [attStr addAttributes:@{NSForegroundColorAttributeName:[UIColor bbxTextHeadTitleColor]} range:NSMakeRange(0, returnRange.location)];
        [attStr addAttributes:@{NSForegroundColorAttributeName:[UIColor bbxTextNoteColor]} range:NSMakeRange(returnRange.location, returnRange.length)];
        
        labTitle.attributedText = attStr;
    }
    
    return labTitle;
}


- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if(self.pickerMode == PickerDateType_Custom)
    {
        YHPickerItem * item = self.dataList[component];
        if(item.pickerDataList.count > 0)
        {
            item.pickerSelectTitle = item.pickerDataList[row];
        }
    }
    else if(self.pickerMode == PickerDateType_Block)
    {
        [self.pickerSelectIndexDicBlock setValue:@(row) forKey:[NSString stringWithFormat:@"%d",(int)component]];
        
        if(self.pickerSelectRowBlock)
        {
            self.pickerSelectRowBlock(component,row);
        }
    }
    else
    {
        PickerDateType type = [self typeShowAtComponent:component];
        switch (type) {
            case PickerDateType_Year:
            {
                //年
                self.pickerDateSelect.year = self.pickerDateSelect.yearMax - row;
                [self reloadDayComponent];
            }
                break;
            case PickerDateType_Month:
            {
                //月
                self.pickerDateSelect.month = row + 1;
                [self reloadDayComponent];
            }
                break;
            case PickerDateType_Day:
            {
                self.pickerDateSelect.day = row + 1;
            }
                break;
            case PickerDateType_Hour:
            {
                //时
                self.pickerDateSelect.hour = row + 1;
            }
                break;
            case PickerDateType_Minute:
            {
                //分
                self.pickerDateSelect.minute = row + 1;
            }
                break;
            case PickerDateType_Second:
            {
                //秒
                self.pickerDateSelect.second = row + 1;
            }
                break;
            default:
                
                break;
        }

        
        NSString * dateStr = [NSString stringWithFormat:@"%d-%02d-%02d %02d:%02d:%02d",(int)self.pickerDateSelect.year,(int)self.pickerDateSelect.month,(int)self.pickerDateSelect.day,(int)self.pickerDateSelect.hour,(int)self.pickerDateSelect.minute,(int)self.pickerDateSelect.second];
        
        self.pickerDateSelect.dateDescrption = dateStr;
        
        NSDate * selectDate = [dateStr changeToDate];
        
        if(!selectDate)
        {
            [self resetOriginAnimation];
        }
        else if(self.picker_able == PickerDateSelectAble_old)
        {
            if([selectDate timeIntervalSinceNow] > 0)
            {
                [self resetOriginAnimation];
            }
        }
        else if(self.picker_able == PickerDateSelectAble_future)
        {
            if([selectDate timeIntervalSinceNow] < 0)
            {
                [self resetOriginAnimation];
            }
        }
    }
}


//一共有几块组件
- (NSInteger)typeShowComponentCount
{
    NSInteger count = 0;
    if(self.pickerMode & PickerDateType_Year)
    {
        count++;
    }
    if(self.pickerMode & PickerDateType_Month)
    {
        count++;
    }
    if(self.pickerMode & PickerDateType_Day)
    {
        count++;
    }
    if(self.pickerMode & PickerDateType_Hour)
    {
        count++;
    }
    if(self.pickerMode & PickerDateType_Minute)
    {
        count++;
    }
    if(self.pickerMode & PickerDateType_Second)
    {
        count++;
    }
    return count;
}

//一共有几块组件
- (NSInteger)typeShowAtComponentIndex:(PickerDateType)type
{
    if(self.pickerMode & type)
    {
        NSInteger index = 0;
        if(self.pickerMode & PickerDateType_Year)
        {
            if(type == PickerDateType_Year)
            {
                return index;
            }
            index++;
        }
        if(self.pickerMode & PickerDateType_Month)
        {
            if(type == PickerDateType_Month)
            {
                return index;
            }
            index++;
        }
        if(self.pickerMode & PickerDateType_Day)
        {
            if(type == PickerDateType_Day)
            {
                return index;
            }
            index++;
        }
        if(self.pickerMode & PickerDateType_Hour)
        {
            if(type == PickerDateType_Hour)
            {
                return index;
            }
            index++;
        }
        if(self.pickerMode & PickerDateType_Minute)
        {
            if(type == PickerDateType_Minute)
            {
                return index;
            }
            index++;
        }
        if(self.pickerMode & PickerDateType_Second)
        {
            if(type == PickerDateType_Second)
            {
                return index;
            }
            index++;
        }
    }
    return -1;
}

//某块组件下是什么日期类型
- (PickerDateType)typeShowAtComponent:(NSInteger)component
{
    NSInteger count = 0;
    if(self.pickerMode & PickerDateType_Year)
    {
        if(component == count)
        {
            return PickerDateType_Year;
        }
        count++;
    }
    if(self.pickerMode & PickerDateType_Month)
    {
        if(component == count)
        {
            return PickerDateType_Month;
        }
        count++;
    }
    if(self.pickerMode & PickerDateType_Day)
    {
        if(component == count)
        {
            return PickerDateType_Day;
        }
        count++;
    }if(self.pickerMode & PickerDateType_Hour)
    {
        if(component == count)
        {
            return PickerDateType_Hour;
        }
        count++;
    }if(self.pickerMode & PickerDateType_Minute)
    {
        if(component == count)
        {
            return PickerDateType_Minute;
        }
        count++;
    }if(self.pickerMode & PickerDateType_Second)
    {
        if(component == count)
        {
            return PickerDateType_Second;
        }
        count++;
    }
    return -1;
}


- (void)reloadDayComponent
{
    NSInteger component = [self typeShowAtComponentIndex:PickerDateType_Day];
    
    if(component > -1)
    {
        [self.datePicker reloadComponent:component];
        
        NSInteger dayCount = [self getDayCountAtSelectMonth];
        if(self.pickerDateSelect.day > dayCount)
        {
            self.pickerDateSelect.day = dayCount;
        }
    }
}


- (void)resetOriginAnimation
{
    if(self.pickerMode == PickerDateType_Custom)
    {
        //设置当前选中的是哪个选项
        [self.dataList enumerateObjectsUsingBlock:^(YHPickerItem * obj, NSUInteger idx, BOOL *stop) {
            if(obj.pickerSelectTitle &&
               ![obj.pickerSelectTitle isEqualToString:@""] &&
               ![obj.pickerSelectTitle isKindOfClass:[NSNull class]])
            {
                if([obj.pickerDataList containsObject:obj.pickerSelectTitle])
                {
                    NSInteger index = [obj.pickerDataList indexOfObject:obj.pickerSelectTitle];
                    [self.datePicker selectRow:index inComponent:idx animated:YES];
                }
            }
        }];
        
        return;
    }
    
    if(self.pickerMode == PickerDateType_Block)
    {
        return;
    }
    
    NSString * dateStr = [NSString stringWithFormat:@"%d-%02d-%02d %02d:%02d:%02d",(int)self.pickerDateSelect.year,(int)self.pickerDateSelect.month,(int)self.pickerDateSelect.day,(int)self.pickerDateSelect.hour,(int)self.pickerDateSelect.minute,(int)self.pickerDateSelect.second];
    
    self.pickerDateSelect.dateDescrption = dateStr;

    self.pickerDateSelect.year = self.pickerDateSelect.currentYear;
    self.pickerDateSelect.month = self.pickerDateSelect.currentMonth;
    self.pickerDateSelect.day = self.pickerDateSelect.currentDay;
    self.pickerDateSelect.hour = self.pickerDateSelect.currentHour;
    self.pickerDateSelect.minute = self.pickerDateSelect.currentMinute;
    self.pickerDateSelect.second = self.pickerDateSelect.currentSecond;

    
    NSInteger offsetYear = self.pickerDateSelect.yearMax - self.pickerDateSelect.year;
    NSInteger offsetMonth = self.pickerDateSelect.currentMonth - 1;
    NSInteger offsetDay = self.pickerDateSelect.currentDay - 1;
    NSInteger offsetHour = self.pickerDateSelect.currentHour - 1;
    NSInteger offsetMintue = self.pickerDateSelect.currentMinute - 1;
    NSInteger offsetSecond = self.pickerDateSelect.currentSecond - 1;
    
    
    NSInteger componentCount = [self typeShowComponentCount];
    for(NSInteger component = 0; component < componentCount; component++)
    {
        PickerDateType type = [self typeShowAtComponent:component];
        
        switch (type) {
            case PickerDateType_Year:
            {
                //年
                [self.datePicker selectRow:offsetYear inComponent:component animated:YES];
            }
                break;
            case PickerDateType_Month:
            {
                //月
                [self.datePicker selectRow:offsetMonth inComponent:component animated:YES];
            }
                break;
            case PickerDateType_Day:
            {
                [self.datePicker selectRow:offsetDay inComponent:component animated:YES];
            }
                break;
            case PickerDateType_Hour:
            {
                //时
                [self.datePicker selectRow:offsetHour inComponent:component animated:YES];
            }
                break;
            case PickerDateType_Minute:
            {
                //分
                [self.datePicker selectRow:offsetMintue inComponent:component animated:YES];
            }
                break;
            case PickerDateType_Second:
            {
                //秒
                [self.datePicker selectRow:offsetSecond inComponent:component animated:YES];
            }
                break;
            default:
                
                break;
        }
    }
}

- (void)creatToolBar
{
    UIView * toolV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 44)];
    self.toolV = toolV;
    toolV.backgroundColor = [UIColor whiteColor];
    
    if(self.pickerTitle)
    {
        UILabel * titleV = [[UILabel alloc] initWithFrame:toolV.bounds];
        titleV.text = self.pickerTitle;
        titleV.textAlignment = NSTextAlignmentCenter;
        titleV.font = [UIFont bbxSystemFont:14];
        titleV.textColor = [UIColor flatGrayColor];
        titleV.autoresizingMask = 0xff;
        [toolV addSubview:titleV];
    }
    
    
    UIButton * btnCancel = [UIButton buttonWithType:UIButtonTypeCustom];
    btnCancel.backgroundColor = [UIColor clearColor];
    [btnCancel setTitle:@"取消" forState:UIControlStateNormal];
    [btnCancel setTitleColor:[UIColor flatGrayColor] forState:UIControlStateNormal];
    btnCancel.titleLabel.font = [UIFont bbxSystemFont:14];
    [btnCancel addTarget:self action:@selector(pickerNumCancel) forControlEvents:UIControlEventTouchUpInside];
    btnCancel.frame = CGRectMake(0, 0, 60, CGRectGetHeight(toolV.frame));
    btnCancel.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight;
    [toolV addSubview:btnCancel];
    
    
    UIButton * btnSubmit = [UIButton buttonWithType:UIButtonTypeCustom];
    btnSubmit.backgroundColor = [UIColor clearColor];
    [btnSubmit setTitle:@"确定" forState:UIControlStateNormal];
    [btnSubmit setTitleColor:[UIColor flatBlueColor] forState:UIControlStateNormal];
    btnSubmit.titleLabel.font = [UIFont bbxSystemFont:14];
    [btnSubmit addTarget:self action:@selector(pickerNumSubmit) forControlEvents:UIControlEventTouchUpInside];
    btnSubmit.frame = CGRectMake(CGRectGetWidth(toolV.frame)-60, 0, 60, CGRectGetHeight(toolV.frame));
    btnSubmit.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
    [toolV addSubview:btnSubmit];
    
    
    UIView * lineV = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(toolV.frame)-0.5, CGRectGetWidth(toolV.frame), 0.5)];
    lineV.backgroundColor = [UIColor bbxBorderAndSepartionLineColor];
    lineV.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [toolV addSubview:lineV];
    
    lineV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(toolV.frame), 0.5)];
    lineV.backgroundColor = [UIColor bbxBorderAndSepartionLineColor];
    lineV.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [toolV addSubview:lineV];
    
    
    [self.view addSubview:toolV];
    
    __weak typeof(&*self)weakSelf = self;
    
    if(self.customTopV)
    {
        [toolV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(weakSelf.view);
            make.bottom.equalTo(weakSelf.customTopV.mas_top);
            make.height.mas_equalTo(44);
        }];
    }
    else
    {
        [toolV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(weakSelf.view);
            make.bottom.equalTo(weakSelf.datePicker.mas_top).offset(20);
            make.height.mas_equalTo(44);
        }];
    }
}

- (NSInteger)getDayCountAtSelectMonth
{
    if(self.pickerDateSelect.month == 1 ||
       self.pickerDateSelect.month == 3 ||
       self.pickerDateSelect.month == 5 ||
       self.pickerDateSelect.month == 7 ||
       self.pickerDateSelect.month == 8 ||
       self.pickerDateSelect.month == 10 ||
       self.pickerDateSelect.month == 12)
    {
        return 31;
    }
    else if (self.pickerDateSelect.month == 2)
    {
        // 2月份,闰年29天、平年28天
        if ((self.pickerDateSelect.year % 4 == 0 && self.pickerDateSelect.year % 100 != 0) ||
            self.pickerDateSelect.year % 400 == 0)
        {
            return 29;
        }
        else
        {
            return 28;
        }
    }
    else
    {
        return 30;
    }
}


- (void)selectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if(component >= [self numberOfComponentsInPickerView:self.datePicker])
    {
        return;
    }
    if(row >= [self pickerView:self.datePicker numberOfRowsInComponent:component])
    {
        return;
    }
    
    [self.datePicker selectRow:row inComponent:component animated:YES];
}


+ (void)showPickerDateWithConfigBlock:(void (^)(YHPickerViewController *))pickerSettingBlock andPickerFinish:(void (^)(id))pickerFinishBlock
{
    YHPickerViewController * pickerVC = [[YHPickerViewController alloc] init];
    
    [pickerVC defaultConfigSetting];
    
    pickerVC.pickerFinishBlock = pickerFinishBlock;
    
    if(pickerSettingBlock)
    {
        pickerSettingBlock(pickerVC);
    }

    [pickerVC showPickerView];
    
    [[UIApplication sharedApplication].keyWindow.rootViewController addChildViewController:pickerVC];
    [[UIApplication sharedApplication].keyWindow.rootViewController.view addSubview:pickerVC.view];
}


@end




@implementation YHDatePickerItem

@end



@implementation YHPickerItem


-(instancetype)initWithTitle:(NSString *)title andPickerList:(NSArray<NSString *> *)list andPickerSelectTitle:(NSString *)selectTitle
{
    self = [super init];
    if(self)
    {
        self.pickerDataList = [NSArray arrayWithArray:list];
        self.pickerTitle = title;
        self.pickerSelectTitle = selectTitle;
    }
    return self;
}


@end



使用例子:

[YHPickerViewController showPickerDateWithConfigBlock:^(YHPickerViewController *pickerVC) {
       
        if(indexPath.row == 0)
        {
            pickerVC.picker_able = PickerDateSelectAble_old;
            
            pickerVC.pickerMode = PickerDateType_Year | PickerDateType_Month| PickerDateType_Day | PickerDateType_Minute | PickerDateType_Second | PickerDateType_Hour;
        }
        else if(indexPath.row == 1)
        {
            pickerVC.pickerMode = PickerDateType_Custom;
            
            YHPickerItem * item1 = [[YHPickerItem alloc] initWithTitle:@"上海" andPickerList:@[@"上海s",@"上海s",@"上海s",@"上海s",@"上海s",@"上海s",@"上海s",@"上海s",@"上海s"] andPickerSelectTitle:@""];
            YHPickerItem * item2 = [[YHPickerItem alloc] initWithTitle:@"北京" andPickerList:@[@"北京s",@"北京s",@"北京s",@"北京s",@"北京s",@"北京s",@"北京",@"上海s",@"上海s"] andPickerSelectTitle:@""];
            YHPickerItem * item3 = [[YHPickerItem alloc] initWithTitle:@"xiamen" andPickerList:@[@"xiamens",@"上海s",@"上海s",@"上海s",@"上海s",@"xiamens",@"上海s",@"上海s",@"上海s"] andPickerSelectTitle:@""];
            
            pickerVC.dataList = @[item1,item2,item3];
        }
        else if (indexPath.row == 3)
        {
            pickerVC.pickerMode = PickerDateType_Block;
            
            [pickerVC setPickerComponentCountBlock:^NSInteger{
                return 10;
            }];
            [pickerVC setPickerRowCountBlock:^NSInteger(NSInteger component){
                if(component == 0)
                {
                    return 10;
                }
                else if (component == 1)
                {
                    return 2;
                }
                return component*2;
            }];
            [pickerVC setPickerTitleRowBlock:^NSString *(NSInteger component,NSInteger row){
                return [NSString stringWithFormat:@"%d_%d",component,row];
            }];
            [pickerVC setPickerSelectRowBlock:^(NSInteger component,NSInteger row){
                NSLog(@"选中%d_%d",component,row);
            }];
        }
        
    } andPickerFinish:^(id selectItems) {
     
        NSLog(@"%@",selectItems);
        
    }];
    

例图:

Paste_Image.png
Paste_Image.png
Paste_Image.png

有什么问题和建议欢迎留言。

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

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,413评论 25 707
  • 废话不多说,直接上干货 ---------------------------------------------...
    小小赵纸农阅读 3,333评论 0 15
  • 内容抽屉菜单ListViewWebViewSwitchButton按钮点赞按钮进度条TabLayout图标下拉刷新...
    皇小弟阅读 46,705评论 22 664
  • 今天回家路上,看到群里有人转了一篇文章《今天我终于取关了同道大叔》。可能是标题党,我点开来看。 没有传说中的惊喜,...
    小衡野阅读 495评论 0 0
  • 1、父类实现深拷贝时,子类如何实现深度拷贝。父类没有实现深拷贝时,子类如何实现深度拷贝。 深拷贝同浅拷贝的区别:浅...
    Mr丶炎阅读 102评论 2 0