iOS-自定義PickerView

weixin_33782386發表於2017-04-24

分享一個自定義的日期選擇控制元件,或者其他自定義選擇項,通過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);
        
    }];
    

例圖:

2019043-733a148e37cb4de0.png
Paste_Image.png
2019043-da7c3dcf958a145f.png
Paste_Image.png
2019043-8865d82a077b2f18.png
Paste_Image.png

有什麼問題和建議歡迎留言。

相關文章