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 * 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 * pickerDataList;
@property (copy, nonatomic)     NSString * pickerSelectTitle;

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

- (instancetype)initWithTitle:(NSString *)title andPickerList:(NSArray *)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 
#import "UIFont+BBX.h"
#import "UIColor+BBXApp.h"
#import "NSString+BBX.h"
#import "NSDate+BBX.h"
#import 





@interface YHPickerViewController()

@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 *)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);
        
    }];
    

例图:

iOS-自定义PickerView_第1张图片
Paste_Image.png
iOS-自定义PickerView_第2张图片
Paste_Image.png
iOS-自定义PickerView_第3张图片
Paste_Image.png

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

你可能感兴趣的:(iOS-自定义PickerView)