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閱讀 229,327評論 6 537
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,996評論 3 423
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,316評論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,406評論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,128評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,524評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,576評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,759評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,310評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,065評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,249評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,821評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,479評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,909評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,140評論 1 290
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,984評論 3 395
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,228評論 2 375

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,690評論 25 708
  • 廢話不多說,直接上干貨 ---------------------------------------------...
    小小趙紙農閱讀 3,402評論 0 15
  • 內容抽屜菜單ListViewWebViewSwitchButton按鈕點贊按鈕進度條TabLayout圖標下拉刷新...
    皇小弟閱讀 46,857評論 22 665
  • 今天回家路上,看到群里有人轉了一篇文章《今天我終于取關了同道大叔》。可能是標題黨,我點開來看。 沒有傳說中的驚喜,...
    小衡野閱讀 506評論 0 0
  • 1、父類實現深拷貝時,子類如何實現深度拷貝。父類沒有實現深拷貝時,子類如何實現深度拷貝。 深拷貝同淺拷貝的區別:淺...
    Mr丶炎閱讀 106評論 2 0