ios日期选择器 - CSDN
精华内容
参与话题
  • ios自定义日期、时间、城市选择器

    千次阅读 2017-05-03 16:19:04
    选择器,我想大家都不陌生,当需要用户去选择某些范围值内的一个固定值时,我们会采用选择器的方式。选择器可以直观的提示用户选择的值范围、统一信息的填写格式,同时也方便用户快速的进行选择,比如对于性别,正常...

    选择器,我想大家都不陌生,当需要用户去选择某些范围值内的一个固定值时,我们会采用选择器的方式。选择器可以直观的提示用户选择的值范围、统一信息的填写格式,同时也方便用户快速的进行选择,比如对于性别,正常情况下就只有男女两种情况,那这时候用一个选择器给用户进行选择的话,可以避免错误数据的输入,也更方便用户去填写。再比如需要获取用户的生日信息时,采用选择器的方式可以统一生日的格式,如果让用户自行输入的话,可能会出现各种各样的生日信息格式,不利于数据的存储,但是采用选择器的方式的话,用户可找到对应的日期进行选择即可。

    在iOS有专门的一个选择器类UIPickerView,进入UIPickerView的头文件,我们可以发现 UIPickerView直接继承了UIView,其事件处理通过代理方法完成,所以创建UIPickerView的时候记得签它的代理UIPickerViewDataSourceUIPickerViewDelegate。其实它和UITbleView有点像,不过UIPickerView还多了个列属性,UITbleView我们都很熟了,所以可以对比UITbleView的相关属性和代理方法来学习记忆UIPickerView。

    一. UIPickerView的代理方法

    (1)UIPickerViewDataSource对应的代理方法有(其代理方法必须要实现):

    返回显示的列数

    - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;

    返回每一列中需要显示的行数

    - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;

    (2)UIPickerViewDelegate对应的代理方法(其代理方法根据需求进行选择性实现):

    返回每一列的宽度

    - (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component;

    返回每一列的高度

    - (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component ;

    返回UIPickerView控件中指定列的列表项的要显示的内容

    - (nullable NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component ;

    返回UIView,作为该UIPickerView控件中指定列的指定行的显示视图

    - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(nullable UIView *)view ;

    选择指定列中的指定行

    - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component ;

    二、UIPickerView和UIDatePicker。

    UIDatePicker是系统帮我们封装好的一个时间日期选择器,继承于UIControl,UIDatePicker有一定的局限性,因为它只有四种显示样式:

    UIDatePickerModeTime,          
    UIDatePickerModeDate,          
    UIDatePickerModeDateAndTime, 
    UIDatePickerModeCountDownTimer, 

    如果需求和这四种样式都不符合的话,那么就没办法使用UIDatePicker,比如当只需要显示年、月信息的时候,显然UIDatePicker没办法满足我们的需求,那这时我们只能通过UIPickerView来自定义自己想要的选择器。

    三、UIPickerView的自定义使用

    (1)创建基类继承于UIView的WXZBasePickView。

    我们常见的选择器的样式是一个带透明背景色的view,底部是内容的选择器,有确定和取消按钮,大致如图:

    选择器

    
所以我们创建一个基类view,这个view的样式如图所示样式,之后根据内容的差别创建基于该view的选择器。

    在.h中声明各个属性及方法

    #import <UIKit/UIKit.h>
    
    @interface WXZBasePickView : UIView
    
    @property (nonatomic, strong) UIView *contentView;
    
    //选择器
    @property (nonatomic, strong)UIPickerView *pickerView;
    //取消按钮
    @property (nonatomic, strong)UIButton *cancelButton;
     //确定按钮
    @property (nonatomic, strong)UIButton *confirmButton;
    
    //选择器每一列的高度
    @property (nonatomic, assign)CGFloat pickerViewHeight;
    
    /**
     *  创建视图,初始化视图时初始数据
     */
    - (void)initPickView;
    
    /**
     *  确认按钮的点击事件
     */
    - (void)clickConfirmButton;
    
    /**
     *  pickerView的显示
     */
    - (void)show;
    
    /**
     *  移除pickerView
     */
    - (void)disMiss;
    
    
    @end

    在.m中实现相关方法

    #import "WXZBasePickView.h"
    #define ScreenWidth [UIScreen mainScreen].bounds.size.width
    #define ScreenHeight [UIScreen mainScreen].bounds.size.height
    @implementation WXZBasePickView
    
    - (instancetype)init
    {
        self = [super init];
        if (self) {
    
            _pickerViewHeight      = 250;
            self.bounds = [UIScreen mainScreen].bounds;
            self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.64];
            self.layer.opacity = 0.0;
    
            UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(disMiss)];
            self.userInteractionEnabled = YES;
            [self addGestureRecognizer:tap];
    
            [self addSubview:self.contentView];
            [self.contentView addSubview:self.pickerView];
            [self.contentView addSubview:self.cancelButton];
            [self.contentView addSubview:self.confirmButton];
    
            [self initPickView];
         }
        return self;
    }
    //初始化选择器内容,创建子类时需实现该父类方法
    -(void)initPickView{
    
    }
    //点击确定按钮
    - (void)clickConfirmButton
    {
        [self disMiss];
    }
    
    //点击取消按钮
    - (void) clickCancelButton
    {
        [self disMiss];
    }
    
    //显示选择器
     - (void)show
    {
        [[UIApplication sharedApplication].keyWindow addSubview:self];
        [self setCenter:[UIApplication sharedApplication].keyWindow.center];
        [[UIApplication sharedApplication].keyWindow bringSubviewToFront:self];
    
    
            CGRect frame =  self.contentView.frame;
           frame.origin.y -= self.contentView.frame.size.height;
            [UIView animateWithDuration:0.4 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self.layer setOpacity:1.0];
                self.contentView.frame = frame;
    
            } completion:^(BOOL finished) {
            }];
    
        }
    
    //移除选择器
    - (void)disMiss
    {
    
            CGRect frame =  self.contentView.frame;
            frame.origin.y += self.contentView.frame.size.height;
            [UIView animateWithDuration:0.4 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self.layer setOpacity:0.0];
                self.contentView.frame = frame;
            } completion:^(BOOL finished) {
                [self removeFromSuperview];
            }];
    
    }
    //设置选择器的高度
    - (void)setPickerViewHeight:(CGFloat)pickerViewHeight
    {
        _pickerViewHeight = pickerViewHeight;
        self.contentView.frame = CGRectMake(self.contentView.frame.origin.x, self.contentView.frame.origin.y, self.contentView.frame.size.width, pickerViewHeight);
    }
    
    - (UIView *)contentView
    {
        if (!_contentView) {
    
            _contentView = [[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight, ScreenWidth, self.pickerViewHeight)];
            [_contentView setBackgroundColor:[UIColor whiteColor]];
        }
        return _contentView;
    }
    
    
    - (UIPickerView *)pickerView
    {
        if (!_pickerView) {
    
            _pickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0,  0, self.contentView.frame.size.width, self.contentView.frame.size.height)];
            [_pickerView setBackgroundColor:[UIColor whiteColor]];
    
        }
        return _pickerView;
    }
    
    - (UIButton *)cancelButton
    {
        if (!_cancelButton) {
    
            _cancelButton = [[UIButton alloc]initWithFrame:CGRectMake(16, 0, 44, 44)];
            [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
            [_cancelButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    
            [_cancelButton.titleLabel setFont:[UIFont systemFontOfSize:16]];
            [_cancelButton addTarget:self action:@selector(clickCancelButton) forControlEvents:UIControlEventTouchUpInside];
        }
        return _cancelButton;
    }
    
    - (UIButton *)confirmButton
    {
        if (!_confirmButton) {
    
            _confirmButton = [[UIButton alloc]initWithFrame:CGRectMake(self.contentView.frame.size.width - self.cancelButton.frame.size.width - self.cancelButton.frame.origin.x, self.cancelButton.frame.origin.y, self.cancelButton.frame.size.width, self.cancelButton.frame.size.height)];
            [_confirmButton setTitle:@"确定" forState:UIControlStateNormal];
            [_confirmButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    
            [_confirmButton.titleLabel setFont:[UIFont systemFontOfSize:16]];
            [_confirmButton addTarget:self action:@selector(clickConfirmButton) forControlEvents:UIControlEventTouchUpInside];
        }
        return _confirmButton;
    }
    
    
    @end
    (2)、自定义一个日期选择器,可选择显示年、月或者年、月、日以及是否显示“至今”选项。

    创建继承于我们自定义好的WXZBasePickView的日期选择器WXZPickDateView

    .h声明相关属性和方法

    #import "WXZBasePickView.h"
    @class WXZBasePickView;
    //选择器的选择代理方法
    @protocol  PickerDateViewDelegate<NSObject>
    - (void)pickerDateView:(WXZBasePickView *)pickerDateView selectYear:(NSInteger)year selectMonth:(NSInteger)month selectDay:(NSInteger)day;
    @end
    
    @interface WXZPickDateView : WXZBasePickView
    
    @property(nonatomic, weak)id <PickerDateViewDelegate>delegate ;
    @property(nonatomic, assign)BOOL isAddYetSelect;//是否增加至今的选项
    @property(nonatomic, assign)BOOL isShowDay;//是否显示日
    //设置默认显示的值
    -(void)setDefaultTSelectYear:(NSInteger)defaultSelectYear defaultSelectMonth:(NSInteger)defaultSelectMonth defaultSelectDay:(NSInteger)defaultSelectDay;
    
    @end

    .m实现相关方法

    #import "WXZPickDateView.h"
    @interface WXZPickDateView()<UIPickerViewDataSource, UIPickerViewDelegate>
    /** 选择的年 */
    @property (nonatomic, assign)NSInteger selectYear;
    /** 选择的月 */
    @property (nonatomic, assign)NSInteger selectMonth;
    /** 选择的日 */
    @property (nonatomic, assign)NSInteger selectDay;
    @property (nonatomic, assign)NSInteger currentYear;
    @property (nonatomic, assign)NSInteger currentMonth;
    @property (nonatomic, assign)NSInteger currentDay;
    @property (nonatomic, assign)NSInteger defaultYear;
    @property (nonatomic, assign)NSInteger defaultMonth;
    @property (nonatomic, assign)NSInteger defaultDay;
    
    @property (nonatomic, assign)NSInteger minShowYear;
    @property (nonatomic, assign)NSInteger yearSum;
    @end
    @implementation WXZPickDateView
    
    - (void)initPickView
    {
        [super initPickView];
        _minShowYear = 1940;//最小年份
        NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
        // 获取当前日期
        NSDate* dt = [NSDate date];
        // 指定获取指定年、月、日、时、分、秒的信息
        unsigned unitFlags = NSCalendarUnitYear |
        NSCalendarUnitMonth |  NSCalendarUnitDay |
        NSCalendarUnitHour |  NSCalendarUnitMinute |
        NSCalendarUnitSecond | NSCalendarUnitWeekday;
        // 获取不同时间字段的信息
        NSDateComponents* comp = [gregorian components: unitFlags fromDate:dt];
    
        _yearSum = comp.year-_minShowYear+1;
        _currentYear=comp.year;
        _currentMonth=comp.month;
        _currentDay=comp.day;
    
    
        _selectYear  = comp.year;
        _selectMonth = comp.month;
        _selectDay   = comp.day;
    
        _defaultYear = comp.year;
        _defaultMonth = comp.month;
        _defaultDay=comp.day;
        [self.pickerView setDelegate:self];
        [self.pickerView setDataSource:self];
    
    }
    -(void)setDefaultTSelectYear:(NSInteger)defaultSelectYear defaultSelectMonth:(NSInteger)defaultSelectMonth defaultSelectDay:(NSInteger)defaultSelectDay{
    
        if (defaultSelectYear!=0) {
         _defaultYear=defaultSelectYear;
        }
    
        if (defaultSelectMonth!=0) {
            _defaultMonth = defaultSelectMonth;
        }
    
        if (defaultSelectDay!=0) {
             _defaultDay=defaultSelectDay;
        }
    
    
        if (defaultSelectYear==-1) {
            _defaultYear=_currentYear+1;
            _defaultMonth=1;
            _defaultDay=1;
        }
    
    
        [self.pickerView selectRow:(_defaultYear - _minShowYear) inComponent:0 animated:NO];
        [self.pickerView reloadComponent:1];
        [self.pickerView selectRow:(_defaultMonth - 1) inComponent:1 animated:NO];
        if (_isShowDay==YES) {
            [self.pickerView reloadComponent:2];
            [self.pickerView selectRow:_defaultDay inComponent:1 animated:NO];
        }
    
        [self refreshPickViewData];
    
    }
    -(void)setIsAddYetSelect:(BOOL)isAddYetSelect{
        _isAddYetSelect = isAddYetSelect;
    }
    
    
    - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
    {
    //判断是否要显示日,如果显示则返回3列,反之返回2列
        if (_isShowDay==YES) {
            return 3;
        }else{
            return 2;
        }
    }
    
    - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
    {
        if (component == 0) {
            if (_isAddYetSelect==YES) {
                //显示至今选项的话,需要比总共要显示的年份多返回一行
                return self.yearSum+1;
    
            }else{
    
               return self.yearSum;
            }
        }else if(component == 1) {
            NSInteger yearSelected = [pickerView selectedRowInComponent:0] + self.minShowYear;
            if (yearSelected==_currentYear+1) {
                //至今选项的时候月份信息不返回
                return 0;
            }else{
    
                return 12;
            }
        }else {
            NSInteger yearSelected = [pickerView selectedRowInComponent:0] + self.minShowYear;
            if (yearSelected==_currentYear+1) {
                 //至今选项的时候日信息不返回
                return 0;
            }else{
            NSInteger yearSelected = [pickerView selectedRowInComponent:0] + self.minShowYear;
            NSInteger monthSelected = [pickerView selectedRowInComponent:1] + 1;
            return  [self getDaysWithYear:yearSelected month:monthSelected];
            }
        }
    
    
    }
    //根据年、月判断日期天数
    - (NSInteger)getDaysWithYear:(NSInteger)year
                           month:(NSInteger)month
    {
        switch (month) {
            case 1:
                return 31;
                break;
            case 2:
                if (year%400==0 || (year%100!=0 && year%4 == 0)) {
                    return 29;
                }else{
                    return 28;
                }
                break;
            case 3:
                return 31;
                break;
            case 4:
                return 30;
                break;
            case 5:
                return 31;
                break;
            case 6:
                return 30;
                break;
            case 7:
                return 31;
                break;
            case 8:
                return 31;
                break;
            case 9:
                return 30;
                break;
            case 10:
                return 31;
                break;
            case 11:
                return 30;
                break;
            case 12:
                return 31;
                break;
            default:
                return 0;
                break;
        }
    }
    - (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
    {
        //每一行的高度
        return 36;
    }
    
    - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
    {
    
        NSInteger selectYear;
        NSInteger selectMonth;
    
        switch (component) {
            case 0:
    
                [pickerView reloadComponent:1];
                if (_isAddYetSelect==YES) {
                    selectYear = row+_minShowYear+1;
                }else{
                    selectYear = row+_minShowYear;
                }
                if (_isShowDay==YES) {
                    [pickerView reloadComponent:2];
                }
                break;
            case 1:
                selectMonth = row+1;
                if (_isShowDay==YES) {
                    [pickerView reloadComponent:2];
                }
            default:
                break;
        }
    
        [self refreshPickViewData];
    
    }
    
    
    - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(nullable UIView *)view
    {
    
        NSString *text;
        if (component == 0) {
    
            if (_isAddYetSelect==YES) {
    
                if (row+_minShowYear==_currentYear+1) {
                    text=@"至今";
    
                }else{
    
    
                    text =  [NSString stringWithFormat:@"%zd年", row + _minShowYear];
    
                }
    
            }else{
    
                text =  [NSString stringWithFormat:@"%zd年", row + _minShowYear];
            }
    
        }else if (component == 1){
            if (_isAddYetSelect==YES) {
                NSInteger yearSelected = [pickerView selectedRowInComponent:0] + self.minShowYear;
                if (yearSelected==_currentYear+1) {
                    text =  [NSString stringWithFormat:@""];
                }else{
                    text =  [NSString stringWithFormat:@"%zd月", row + 1];
                }
            }else{
                text =  [NSString stringWithFormat:@"%zd月", row + 1];
            }
    
    
        }else{
            text = [NSString stringWithFormat:@"%zd日", row + 1];
        }
    
        UILabel *label = [[UILabel alloc]init];
        label.textAlignment = 1;
        label.font = [UIFont systemFontOfSize:16];
        label.text = text;
    
        return label;
    }
    
    
    - (void)clickConfirmButton
    {
    
    
        if ([self.delegate respondsToSelector:@selector(pickerDateView:selectYear:selectMonth:selectDay:)]) {
    
            [self.delegate pickerDateView:self selectYear:self.selectYear selectMonth:self.selectMonth selectDay:self.selectDay];
    
        }
    
        [super clickConfirmButton];
    
    }
    
    
    
    - (void)refreshPickViewData
    {
    
        self.selectYear  = [self.pickerView selectedRowInComponent:0] + self.minShowYear;
    
        self.selectMonth = [self.pickerView selectedRowInComponent:1] + 1;
        if (_isShowDay==YES) {
              self.selectDay   = [self.pickerView selectedRowInComponent:2] + 1;
        }
    
    }
    
    
    - (void)setYearLeast:(NSInteger)yearLeast
    {
        _minShowYear = yearLeast;
    }
    
    - (void)setYearSum:(NSInteger)yearSum
    {
        _yearSum = yearSum;
    }
    
    -(void)setIsShowDay:(BOOL)isShowDay{
        _isShowDay=isShowDay;
    }
    
    @end
    (3) 创建继承于WXZBasePickView的时间选择器WXZPickTimeView。

    .h声明属性及相关方法

    #import "WXZBasePickView.h"
    @class WXZPickTimeView;
    
    @protocol  PickTimeViewDelegate<NSObject>
    - (void)pickerTimeView:(WXZPickTimeView *)pickerTimeView selectHour:(NSInteger)hour selectMinute:(NSInteger)minute ;
    
    @end
    @interface WXZPickTimeView : WXZBasePickView
    @property(nonatomic, weak)id <PickTimeViewDelegate>delegate ;
    
    -(void)setDefaultHour:(NSInteger)hour defaultMinute:(NSInteger)minute  ;
    @end

    .m实现相关方法

    #import "WXZPickTimeView.h"
    @interface WXZPickTimeView () <UIPickerViewDataSource, UIPickerViewDelegate>{
        UIDatePicker    *_datePicker;
    }
    
    @property (nonatomic, assign)NSInteger selectHour;
    @property (nonatomic, assign)NSInteger selectMinute;
    @property (nonatomic, assign)NSInteger day;
    @property (nonatomic, assign)NSInteger defaultHour;
    @property (nonatomic, assign)NSInteger defaultMinute;
    
    @end
    
    @implementation WXZPickTimeView
    
     - (void)initPickView
    {
        [super initPickView];
    
    
        NSCalendar *gregorian = [[NSCalendar alloc]
                                 initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
        // 获取当前日期
        NSDate* dt = [NSDate date];
        // 定义一个时间字段的旗标,指定将会获取指定年、月、日、时、分、秒的信息
        unsigned unitFlags = NSCalendarUnitYear |
        NSCalendarUnitMonth |  NSCalendarUnitDay |
        NSCalendarUnitHour |  NSCalendarUnitMinute |
        NSCalendarUnitSecond | NSCalendarUnitWeekday;
        // 获取不同时间字段的信息
        NSDateComponents* comp = [gregorian components: unitFlags
                                              fromDate:dt];
    
        _selectHour=comp.hour;
        _selectMinute=comp.minute;
    
        [self.pickerView setDelegate:self];
        [self.pickerView setDataSource:self];
    
        [self.pickerView selectRow:_selectHour inComponent:0 animated:NO];
        [self.pickerView selectRow:_selectMinute inComponent:1 animated:NO];
    
    
    }
    -(void)setDefaultHour:(NSInteger)hour defaultMinute:(NSInteger)minute{
    
        if (hour!=0) {
    
         _defaultHour=hour;
    
    
        }else{
            _defaultHour=_selectHour;
    
        }
        if (minute!=0) {
    
    
            _defaultMinute = minute;
    
        }else{
    
            _defaultMinute=_selectMinute;
        }
        [self.pickerView selectRow:_defaultHour inComponent:0 animated:NO];
        [self.pickerView reloadComponent:1];
        [self.pickerView selectRow:_defaultMinute inComponent:1 animated:NO];
        [self refreshPickTimeViewData];
    
    }
    
    - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
    {
        return 2;
    }
    
    - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
    {
        if (component == 0) {
            return 24;
        }else {
            return 60;
        }
    }
    
    - (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
    {
        return 36;
    }
    
    - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
    {
        switch (component) {
            case 0:
                [pickerView reloadComponent:1];
    
                break;
            case 1:
    
            default:
                break;
        }
    
        [self refreshPickTimeViewData];
    }
    
    - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(nullable UIView *)view
    {
    
        NSString *text;
        if (component == 0) {
            if (row<10) {
                text =  [NSString stringWithFormat:@"0%zd时", row];
            }else{
                text =  [NSString stringWithFormat:@"%zd时", row];
            }
        }else if (component == 1){
            if (row<10) {
                text =  [NSString stringWithFormat:@"0%zd分", row ];
            }else{
                text =  [NSString stringWithFormat:@"%zd分", row ];
            }
        }else{
    
        }
    
        UILabel *label = [[UILabel alloc]init];
        label.textAlignment = 1;
        label.font = [UIFont systemFontOfSize:16];
        label.text = text;
        return label;
    }
    
    - (void)clickConfirmButton
    {
        if ([self.delegate respondsToSelector:@selector(pickerTimeView:selectHour:selectMinute:)]) {
    
            [self.delegate pickerTimeView:self selectHour:self.selectHour selectMinute:self.selectMinute];
    
        }
    
        [super clickConfirmButton];
    }
    
    - (void)refreshPickTimeViewData
    {
        self.selectHour  = [self.pickerView selectedRowInComponent:0];
        self.selectMinute = [self.pickerView selectedRowInComponent:1];
    
    }
    @end
    (4)创建继承于WXZBasePickView的城市选择器WXZPickCityView。

    .h声明相关属性和方法

    #import "WXZBasePickView.h"
    @class WXZPickCityView;
    
    @protocol  PickerCityViewDelegate<NSObject>
    
    - (void)pickerArea:(WXZPickCityView *)pickerArea selectProvince:(NSString *)province selectCity:(NSString *)city;
    
    @end
    @interface WXZPickCityView : WXZBasePickView
    @property(nonatomic, weak)id <PickerCityViewDelegate>delegate ;
    
    /**设置默认的省市*/
    
    -(void)setDefaultCity:(NSString *)defaultCity  DefaultProvience:(NSString *)defaultProvience;
    @end
    

    .m实现相关方法

    #import "WXZPickCityView.h"
    @interface WXZPickCityView()<UIPickerViewDataSource, UIPickerViewDelegate>
    
    
    @property (nonatomic, strong, nullable)NSArray *areaDataSource;
    
    @property (nonatomic, strong, nullable)NSMutableArray *provinceArray;
    
    @property (nonatomic, strong, nullable)NSMutableArray *cityArray;
    
    @property (nonatomic, strong, nullable)NSMutableArray *selectedArray;//当前选中的数组
    
    @property (nonatomic, strong, nullable)NSString *selectProvince;
    
    @property (nonatomic, strong, nullable)NSString *selectCity;
    
    @end
    
    @implementation WXZPickCityView
    
    
    - (void)initPickView
    {
        [super initPickView];
        for (NSDictionary *dic in self.areaDataSource) {
            [self.provinceArray addObject:dic[@"state"]];
        }
    
        NSMutableArray *citysArr = [NSMutableArray arrayWithArray:[self.areaDataSource firstObject][@"cities"]];
    
    
        for (NSDictionary *dic in citysArr) {
            [self.cityArray addObject:dic[@"city"]];
        }
    
        self.selectProvince = self.provinceArray[0];
        self.selectCity = self.cityArray[0];
    
    
        [self.pickerView setDelegate:self];
        [self.pickerView setDataSource:self];
    
    }
    
    //设置默认显示的省市
    -(void)setDefaultCity:(NSString *)defaultCity DefaultProvience:(NSString *)defaultProvience{
    
        for (NSInteger i = 0; i<_provinceArray.count; i++) {
    
            if ([_provinceArray[i] isEqualToString:defaultProvience]) {
    
                [self.pickerView selectRow:i inComponent:0 animated:NO];
                self.selectedArray = self.areaDataSource[i][@"cities"];
    
                [self.cityArray removeAllObjects];
                [self.selectedArray enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    [self.cityArray addObject:obj[@"city"]];
                }];
                for (NSInteger j= 0; j<_cityArray.count; j++) {
    
                    if ([defaultCity isEqualToString:_cityArray[j]]) {
    
                        [self.pickerView selectRow:i inComponent:0 animated:NO];
                        [self.pickerView reloadComponent:1];
                        [self.pickerView selectRow:j inComponent:1 animated:NO];
                        [self refreshSelectAreaData];
                    }
                }
            }
    
    
        }
    
    }
    
    
    - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
    {
        return 2;
    }
    
    - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
    {
        if (component == 0) {
            return self.provinceArray.count;
        }else  {
            return self.cityArray.count;
        }
    }
    
    - (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
    {
        return 36;
    }
    
    - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
    {
        if (component == 0) {
            self.selectedArray = self.areaDataSource[row][@"cities"];
    
            [self.cityArray removeAllObjects];
            [self.selectedArray enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [self.cityArray addObject:obj[@"city"]];
            }];
    
    
            [pickerView reloadComponent:1];
            [pickerView selectRow:0 inComponent:1 animated:YES];
    
    
        }else if (component == 1) {
            if (self.selectedArray.count == 0) {
                self.selectedArray = [self.areaDataSource firstObject][@"cities"];
            }
    
        }else{
        }
    
        [self refreshSelectAreaData];
    }
    
    - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(nullable UIView *)view
    {
    
        for(UIView *singleLine in pickerView.subviews)
        {
            if (singleLine.frame.size.height < 1)
            {
                singleLine.backgroundColor =[UIColor grayColor];
            }
        }
        NSString *text;
        if (component == 0) {
            text =  self.provinceArray[row];
        }else if (component == 1){
            text =  self.cityArray[row];
        }else{
    
        }
    
        UILabel *label = [[UILabel alloc]init];
        label.textAlignment = 1;
        label.font = [UIFont systemFontOfSize:16];
        label.text = text;
    
        return label;
    }
    
    
    - (void)clickConfirmButton
    {
    
        [self.delegate pickerArea:self selectProvince:self.selectProvince selectCity:self.selectCity];
    
        [super clickConfirmButton];
    }
    
    
    - (void)refreshSelectAreaData
    {
        NSInteger provienceIndex = [self.pickerView selectedRowInComponent:0];
        NSInteger cityIndex = [self.pickerView selectedRowInComponent:1];
    
        self.selectProvince = self.provinceArray[provienceIndex];
        self.selectCity = self.cityArray[cityIndex];
    
    
    }
    
    
    
    - (NSArray *)areaDataSource
    {
        if (!_areaDataSource) {
            NSString *path = [[NSBundle bundleForClass:[WXZPickCityView class]] pathForResource:@"area" ofType:@"plist"];
            _areaDataSource = [[NSArray alloc]initWithContentsOfFile:path];
        }
        return _areaDataSource;
    }
    
    - (NSMutableArray *)provinceArray
    {
        if (!_provinceArray) {
            _provinceArray = [NSMutableArray array];
        }
        return _provinceArray;
    }
    
    - (NSMutableArray *)cityArray
    {
        if (!_cityArray) {
            _cityArray = [NSMutableArray array];
        }
        return _cityArray;
    }
    
    
    
    - (NSMutableArray *)selectedArray
    {
        if (!_selectedArray) {
            _selectedArray = [NSMutableArray array];
        }
        return _selectedArray;
    }
    
    
    
    @end
    
    (5)创建继承于WXZBasePickView的单列选择器WXZCustomPickView,可根据传进来的数组显示相关的选择内容

    .h声明相关属性和方法

    #import "WXZBasePickView.h"
    
    @class WXZCustomPickView;
    
    @protocol  CustomPickViewDelegate<NSObject>
    - (void)customPickView:(WXZCustomPickView *)customPickView selectedTitle:(NSString *)selectedTitle;
    @end
    
    @interface WXZCustomPickView :WXZBasePickView
    
    @property (nonatomic, strong)NSMutableArray *dataArray;
    @property(nonatomic, copy)NSString *defalutSelectRowStr;
    @property(nonatomic, weak)id <CustomPickViewDelegate>delegate;
    @end

    .m实现相关方法

    #import "WXZCustomPickView.h"
    @interface WXZCustomPickView()<UIPickerViewDataSource, UIPickerViewDelegate>
    /** 1.选中的字符串 */
    @property (nonatomic, strong, nullable)NSString *selectedTitle;
    
    @end
    
    @implementation WXZCustomPickView
    
    
    - (void)initPickView
    {
        [super initPickView];
    
        _dataArray=[NSMutableArray mutableCopy];
    
    
    
        [self.pickerView setDelegate:self];
        [self.pickerView setDataSource:self];
    
    
    
    
    }
    
    -(void)setDefalutSelectRowStr:(NSString *)defalutSelectRowStr{
        _defalutSelectRowStr=defalutSelectRowStr;
    
        for (NSInteger i = 0; i<_dataArray.count; i++) {
    
    
            if ([_dataArray[i] isEqualToString:_defalutSelectRowStr]) {
                [self.pickerView reloadAllComponents];
                [self.pickerView selectRow:i inComponent:0 animated:NO];
    
            }
        }
    }
    
    
    - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
    {
        return 1;
    }
    
    - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
    {
        return self.dataArray.count;
    }
    
    - (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
    {
        return 36;
    }
    
    - (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
    {
    
        return self.frame.size.width;
    
    }
    
    - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
    {
        self.selectedTitle = self.dataArray[row];
    }
    
    - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(nullable UIView *)view
    {
    
        for(UIView *singleLine in pickerView.subviews)
        {
            if (singleLine.frame.size.height < 1)
            {
                singleLine.backgroundColor =[UIColor grayColor];
            }
        }
    
        UILabel *label = [[UILabel alloc]init];
        label.font=[UIFont systemFontOfSize:16];
        label.textAlignment = 1;
    
        label.text=self.dataArray[row];
    
            return label;
    
    
    
    }
    #pragma mark -点击确定按钮
    - (void)clickConfirmButton
    {
        [self.delegate customPickView:self selectedTitle:self.selectedTitle];
    
        [super clickConfirmButton];
    }
    
    
    - (void)setDataArray:(NSMutableArray *)dataArray
    {
        _dataArray = dataArray;
        _selectedTitle = dataArray.firstObject;
        [self.pickerView reloadAllComponents];
    
    }
    
    
    
    @end

    这样,几种类型的选择器我们都定义好了,在需要选择器的地方,根据需求创建相应的选择器即可。

    四、如何使用已创建好的自定义选择器

    引入自定义好的选择器,声明相关属性,签相关协议

    #import "ViewController.h"
    #import "WXZPickDateView.h"
    #import "WXZPickAreaView.h"
    #import "WXZPickTimeView.h"
    #import "WXZCustomPickView.h"
    @interface ViewController ()<PickerDateViewDelegate,PickerAreaViewDelegate,PickTimeViewDelegate,CustomPickViewDelegate>{
        UIButton *dateButton;
        UIButton *selectAreabutton;
        UIButton *selectTimeButton;
        UIButton *singlePickViewSelectButton;
        BOOL isShowDay;//是否显示日信息
    }
    
    @end

    创建相应的按钮,触发相应的选择器

    - (void)viewDidLoad {
        [super viewDidLoad];
    
        dateButton=[UIButton buttonWithType:UIButtonTypeCustom];
        dateButton.frame=CGRectMake(100, 100, 100, 50);
        [dateButton setTitle:@"选择日期" forState:UIControlStateNormal];
        [self.view addSubview:dateButton];
        [dateButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [dateButton addTarget:self action:@selector(pickViewSelect:) forControlEvents:UIControlEventTouchUpInside];
        dateButton.tag = 1000;
    
          selectAreabutton=[UIButton buttonWithType:UIButtonTypeCustom];
        selectAreabutton.frame=CGRectMake(100, 200, 100, 50);
        [selectAreabutton setTitle:@"选择地区" forState:UIControlStateNormal];
        [self.view addSubview:selectAreabutton];
        [selectAreabutton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [selectAreabutton addTarget:self action:@selector(pickViewSelect:) forControlEvents:UIControlEventTouchUpInside];
        selectAreabutton.tag = 1001;
        selectTimeButton=[UIButton buttonWithType:UIButtonTypeCustom];
        selectTimeButton.frame=CGRectMake(100, 300, 100, 50);
        [selectTimeButton setTitle:@"选择时间" forState:UIControlStateNormal];
        [self.view addSubview:selectTimeButton];
        [selectTimeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [selectTimeButton addTarget:self action:@selector(pickViewSelect:) forControlEvents:UIControlEventTouchUpInside];
        selectTimeButton.tag = 1002;
    
        singlePickViewSelectButton=[UIButton buttonWithType:UIButtonTypeCustom];
        singlePickViewSelectButton.frame=CGRectMake(100, 400, 100, 50);
        [singlePickViewSelectButton setTitle:@"单个数据选择器" forState:UIControlStateNormal];
        [self.view addSubview:singlePickViewSelectButton];
        [singlePickViewSelectButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [singlePickViewSelectButton addTarget:self action:@selector(pickViewSelect:) forControlEvents:UIControlEventTouchUpInside];
        singlePickViewSelectButton.tag = 1003;
    
    }

    按钮的点击事件:

    -(void)pickViewSelect:(UIButton *)button{
        if (button.tag==1000) {
    
               WXZPickDateView *pickerDate = [[WXZPickDateView alloc]init];
    
    
                [pickerDate setIsAddYetSelect:YES];//是否显示至今选项
                [pickerDate setIsShowDay:YES];//是否显示日信息
                [pickerDate setDefaultTSelectYear:2007 defaultSelectMonth:4 defaultSelectDay:1];//设定默认显示的日期
                [pickerDate setValidTime:2010];
    
                [pickerDate setDelegate:self];
    
               [pickerDate show];
        }else if (button.tag==1001){
            WXZPickAreaView *pickerArea = [[WXZPickAreaView alloc]init];
    
            [pickerArea setDelegate:self];
    
            [pickerArea setDefaultCity:@"上海" DefaultProvience:@"上海"];
    
            [pickerArea show];
            [self.view endEditing:YES];
        }else if (button.tag==1002){
            WXZPickTimeView *pickerArea = [[WXZPickTimeView alloc]init];
    
            [pickerArea setDelegate:self];
    
            [pickerArea setDefaultHour:14 defaultMinute:20];
    
            [pickerArea show];
            [self.view endEditing:YES];
        }else{
            NSMutableArray *arrayData = [NSMutableArray arrayWithObjects:@"2k以下",@"2k-5k",@"5k-10k",@"10k-15k",@"15k-25k",@"25k-50k",@"50k以上", nil];
    
            WXZCustomPickView *pickerSingle = [[WXZCustomPickView alloc]init];
    
            [pickerSingle setDataArray:arrayData];
            [pickerSingle setDefalutSelectRowStr:arrayData[0]];
    
    
            [pickerSingle setDelegate:self];
    
            [pickerSingle show];
            [self.view endEditing:YES];
    
        }
    }

    选择器的代理方法

    -(void)pickerDateView:(WXZBasePickView *)pickerDateView selectYear:(NSInteger)year selectMonth:(NSInteger)month selectDay:(NSInteger)day{
        NSLog(@"选择的日期是:%ld %ld %ld",year,month,day);
        if (isShowDay==YES) {
            [dateButton setTitle:[NSString stringWithFormat:@"%ld年 %ld月 %ld日",year,month,day] forState:UIControlStateNormal];
        }else{
            [dateButton setTitle:[NSString stringWithFormat:@"%ld年 %ld月",year,month] forState:UIControlStateNormal];
        }
    
    }
    
    -(void)pickerArea:(WXZPickAreaView *)pickerArea selectProvince:(NSString *)province selectCity:(NSString *)city{
        NSLog(@"省市的选择%@ %@",province,city);
        [selectAreabutton setTitle:[NSString stringWithFormat:@"%@%@",province,city] forState:UIControlStateNormal];
    }
    
    -(void)customPickView:(WXZCustomPickView *)customPickView selectedTitle:(NSString *)selectedTitle{
        NSLog(@"选择%@",selectedTitle);
        [singlePickViewSelectButton setTitle:selectedTitle forState:UIControlStateNormal];
    }
    -(void)pickerTimeView:(WXZPickTimeView *)pickerTimeView selectHour:(NSInteger)hour selectMinute:(NSInteger)minute{
        NSLog(@"选择的时间:%ld %ld",hour,minute);
        [selectTimeButton setTitle:[NSString stringWithFormat:@"%ld时 %ld分",hour,minute] forState:UIControlStateNormal];
    }

    最后,看看效果图:

    选择器demo效果图

    有需要的可以下载demo看看

    demo地址

    展开全文
  • iOS日期选择器

    2017-10-08 12:09:31
    日期选择器XFDataSelectView这里我就不废话了,直接上代码。如果对源码感兴趣的,可以研究一下。1.声明以及初始化XFDateSelectView* temp = [[XFDateSelectView alloc]init]; temp.title = @"展示的标题"; 2.使用 ...

    日期选择器XFDataSelectView

    这里我就不废话了,直接上代码。如果对源码感兴趣的,可以研究一下。
    1.声明以及初始化
    
    XFDateSelectView* temp = [[XFDateSelectView alloc]init];
    temp.title = @"展示的标题";
    
    
    2.使用
    [temp showInView:self.view andFixedComplate:^(NSDate *date) {
    
        NSLog(@"%@", date);
    
    }];
    
    
    

    效果图
    这里写图片描述
    这里写图片描述

    展开全文
  • ios-日历选择器.zip

    2020-07-30 23:31:40
    本实例根据日历选择相应日期,并在年月切换的时候确定当前时间!
  • IOS控件-UIDatePicker日期选择器

    千次阅读 2018-11-16 09:22:09
    创建一个DatePicker控件 let datePicker = UIDatePicker()  //设置日期拾取对象的中心点位置  datePicker.center = CGPoint(x: 160, y: 200)  datePicker.tag=1  //设置日期最小值  datePicker.minimum...

    创建一个DatePicker控件

    let datePicker = UIDatePicker()
            //设置日期拾取器对象的中心点位置
            datePicker.center = CGPoint(x: 160, y: 200)
            datePicker.tag=1
            //设置日期最小值
            datePicker.minimumDate=Date()
            //最大值为之后的三天
            datePicker.minimumDate = Date(timeInterval: 3*24*60*60, since: Date())
            self.view.addSubview(datePicker)
    

    添加一个button 

    let button=UIButton(frame: CGRect(x: 20, y: 360, width: 280, height: 44))
            button.setTitle("get date", for: UIControlState())
            button.backgroundColor=UIColor.brown
            button.addTarget(self, action: #selector(ViewController.showDatePicker(_ :)), for: UIControlEvents.touchUpInside)
            self.view.addSubview(button)
    

    绑定一个点击事件

    @objc func showDatePicker(_ button:UIButton){
            //通过tag找到datePicker
            let datePicker=self.view.viewWithTag(1) as! UIDatePicker
            //获得datePicker的日期值
            let date=datePicker.date
            //新建一个日期格式化对象 用来格式化日期
            let dateFormatter = DateFormatter()
            //设置日期的格式
            dateFormatter.dateFormat="yyyy--MM--dd HH:mm"
            //将日期转换为指定字符串
            let dateAndTime = dateFormatter.string(from: date)
            
            let dialog = UIAlertController(title: "title", message: dateAndTime, preferredStyle: UIAlertControllerStyle.alert)
            let ok = UIAlertAction(title: "ok", style: UIAlertActionStyle.default, handler: nil)
            dialog.addAction(ok)
            self.present(dialog,animated: true,completion: nil)
        }
    

     

     

     

     

     

     

     

     

     

     

     

     

    展开全文
  • iOS日期选择器(UIDatePicker)

    千次阅读 2015-12-31 11:10:26
    日期选择器(UIDatePicker)继承了UIControl,因此UIDatePicker可以作为活动控件使用,能与用户交互,既可在Interface Builder中为UIDatePicker的Value Changed事件绑定IBAction事件处理方法,也可在代码中为该...

    UIDatePicker是一个可以用来选择日期和时间的控件。除此之外,它也可作为倒计时控件。

    日期选择器(UIDatePicker)继承了UIControl,因此UIDatePicker可以作为活动控件使用,能与用户交互,既可在Interface Builder中为UIDatePickerValue Changed事件绑定IBAction事件处理方法,也可在代码中为该控件绑定事件处理方法。

    Interface Builder中选中一个UIDatePicker,打开对应的属性检查器面板,即可看到如图10.42所示的面板。

    10.42  UIDatePicker对应的属性检查器


    从图10.42可以看出,UIDatePicker支持如下属性。

    1. Mode

    该属性用于设置该UIDatePicker的模式,它支持如下列表项。

    Ø Date:该UIDatePicker控件仅显示日期,不显示时间。

    Ø Time:该UIDatePicker控件仅显示时间,不显示日期。

    Ø Date and Time:该UIDatePicker控件同时显示日期和时间。

    Ø Count Down Timer:该UIDatePicker控件仅显示为倒计时器。

    2. Locale

    该属性用于设置该UIDatePicker的国际化Locale,假设设置该UIDatePicker控件国际化Locale为简体中文环境,那么它将以简体中文习惯显示日期。实际上,我们通常无须手动设置Locale,该UIDatePicker控件默认使用iOS系统的国际化Locale

    3. Interval

    仅当该UIDatePicker控件采用TimeDate and TimeCount Down Timer这三种模式时有效,该属性设置UIDatePicker控件上两个时间之间的间隔。

    4. Constraints

    该属性为UIDatePicker控件设置最小时间和最大时间。如果设置了该属性值,用户无法通过该UIDatePicker控件选择超出该范围的日期和时间。

    5. Timer

    仅当该UIDatePicker控件采用Count Down Timer模式时有效,该属性设置该控件作为倒计时控件时剩下的秒数。

    下面通过一个简单的例子来示范UIDatePicker的功能和用法,先创建一个Single View Application,并使用Interface Builder打开应用的界面设计文件,将UIDatePickerUIButton拖入应用界面中。对UIDatePicker进行如下修改。

    Ø 使用Date and Time模式,让该选择器同时显示日期和时间。

    Ø 将该UIDatePickerLocale设为Chinese(Simplified),强制该UIDatePicker显示简体中文。

    Ø 勾选Minimum DateMaximum Date,并设置一个最小时间和最大时间。

    进行上面的修改之后,将UIDatePickerUIButton两个控件摆放整齐,如图10.43所示。

    10.43  设计应用界面


    程序界面设计完成之后,在Interface Builder中将UIDatePicker控件绑定到datePicker IBOutlet属性,并为按钮的Touch Up Inside事件绑定clicked: IBAction事件处理方法。经过上面所示的步骤之后,接下来修改控制器类的实现部分代码,主要是实现clicked:事件处理方法,其代码如下。

    程序清单:codes/10/10.11/UIDatePickerTest/UIDatePickerTest/FKViewController.m

    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    @implementation FKViewController
    - (void)viewDidLoad
    {
        [super viewDidLoad];
    }
    - (IBAction)clicked:(id)sender {
        // 获取用户通过UIDatePicker设置的日期和时间
        NSDate *selected = [self.datePicker date];
        // 创建一个日期格式器
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        // 为日期格式器设置格式字符串
        [dateFormatter setDateFormat:@"yyyy年MM月dd日 HH:mm +0800"];
        // 使用日期格式器格式化日期、时间
        NSString *destDateString = [dateFormatter stringFromDate:selected];
        NSString *message =  [NSString stringWithFormat:
            @"您选择的日期和时间是:%@", destDateString];
        // 创建一个UIAlertView对象(警告框),并通过该警告框显示用户选择的日期、时间
        UIAlertView *alert = [[UIAlertView alloc]
            initWithTitle:@"日期和时间"
            message:message
            delegate:nil
            cancelButtonTitle:@"确定"
            otherButtonTitles:nil];
        // 显示UIAlertView
        [alert show];
    }
    @end

    上面程序中,clicked:方法的粗体字代码先获取UIDatePicker控件的日期、时间,然后程序创建了一个NSDateFormatter对象(日期格式器),并使用该日期格式器对用户选择的日期、时间执行格式化。最后使用一个UIAlertView显示用户选择的日期、时间。

    编译、运行该程序,并通过UIDatePicker控件选择一个日期、时间,然后单击“确定”按钮,即可看到如图10.44所示的效果。


    实例:倒计时器

    如果将UIDatePicker的模式设置为Count Down Timer,即可让该控件作为倒计时器使用。当将UIDatePicker作为倒计时器使用时,程序还应该启动一个定时器定期更新该UIDatePicker的剩余时间。由此可见,把UIDatePicker作为Count Down Timer模式使用时,该控件最重要的属性就是countDownDuration,该属性代表该倒计时器的剩余时间,程序既可通过countDownDuration属性获取该控件的剩余时间,也可通过修改该属性来改变该控件显示的剩余时间。

    下面通过示例介绍倒计时器的用法。首先创建一个Single View Application,并使用Interface Builder打开应用的界面设计文件,将UIDatePickerUIButton拖入应用界面中。将UIDatePicker改为Count Down Timer模式,让该选择器作为定时器使用。进行上面的修改之后,将UIDatePickerUIButton两个控件摆放整齐。

    界面设计完成之后,在Interface Builder中将UIDatePicker控件绑定到countDown IBOutlet属性,将按钮控件绑定到startBn IBOutlet属性,并为按钮的Touch Up Inside事件绑定clicked: IBAction事件处理方法。经过上面的步骤之后,下面来修改控制器类的实现部分代码,主要是实现clicked:事件处理方法,其代码如下。

    程序清单:codes/10/10.11/CountDownTest/CountDownTest/FKViewController.m

    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    @implementation FKViewController
    NSTimer* timer;
    NSInteger leftSeconds;  // ①
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // 设置使用Count Down Timer模式
        self.countDown.datePickerMode = UIDatePickerModeCountDownTimer;
    }
    - (IBAction)clicked:(id)sender {
        // 获取该倒计时器的剩余时间
        leftSeconds = self.countDown.countDownDuration;
        // 禁用UIDatePicker控件和按钮
        self.countDown.enabled = NO;
        [sender setEnabled:NO];
        // 初始化一个字符串
        NSString *message =  [NSString stringWithFormat:
            @"开始倒计时?您还剩下【%d】秒", leftSeconds];
        // 创建一个UIAlertView(警告框)
        UIAlertView *alert = [[UIAlertView alloc]
                            initWithTitle:@"开始倒计时?"
                            message:message
                            delegate:nil
                            cancelButtonTitle:@"确定"
                            otherButtonTitles:nil];
        // 显示UIAlertView控件
        [alert show];
        // 启用计时器,控制每隔60秒执行一次tickDown方法
        timer = [NSTimer scheduledTimerWithTimeInterval:60
            target:self selector:@selector(tickDown)
            userInfo:nil repeats:YES];
    }
    - (void) tickDown
    {
        leftSeconds -= 60;  // 将剩余时间减少60秒
        self.countDown.countDownDuration = leftSeconds;  // 修改UIDatePicker的剩余时间
        if(leftSeconds <= 0)  // 如果剩余时间小于或等于0
        {
            // 取消定时器
            [timer invalidate];
            // 启用UIDatePicker控件和按钮
            self.countDown.enabled = YES;
            self.startBn.enabled = YES;
        }
    }
    @end

    上述程序中,①号粗体字代码定义了一个leftSeconds变量,该变量用于保存倒计时器的剩余时间,当用户单击程序界面时,将会激发clicked:方法,该方法将启动一个定时器控制每隔60秒执行一次tickDown方法,而tickDown方法每执行一次,程序就将倒计时器的剩余时间减少60,并动态修改倒计时器的剩余时间,这样就可让UIDatePicker显示的剩余时间减少。

    编译、运行该程序,通过UIDatePicker设置倒计时器的剩余时间后,单击“开始”按钮,即可看到该倒计时器每隔60秒跳动一次,跳动一次后,剩余时间减少1分钟,如图10.45所示。


    ————本文节选自《疯狂ios讲义(上)》

    展开全文
  • iOS 自定义时间选择器 DatePicker

    千次阅读 2018-11-15 11:42:59
    6种时间选择方式: 年月日、年月日时、年月日时分、时分、日时分、月日时分 调用方式 [[DatePicker shareManager]showWithType:PickerTypeDay title:nil time:@&amp;quot;2018:10:31&amp;quot; back...
  • IOS 日期选择器 UIDatePicker的使用

    千次阅读 2016-03-06 01:41:26
    在这 我会给大家分享一个自己写的小程序,详细... 功能,当点击这行cell的时候,会从弹出如图的这个一个日期选择器,然后 选择时间,再把这个时间设置给副标题显示出来 该如何实现呢?????? 下面就不给大家引
  • iOS 日期选择器

    2020-07-17 17:52:50
    日期选择器,日期时间选择,时间选择器,年月日时分 -_-!
  • https://blog.csdn.net/m0_37761307/article/details/78559715 原文github地址: https://github.com/Bigkoo/Android-PickerView
  • iOS 日期选择器 FlatDatePicker ,FlatDatePicker 是一个扁平化风格的 iOS 日期选择器
  • vue ios 日期选择 顺畅选择器 (vue-smooth-picker) Let's more easily select some data on the touch screen device, such as time / city / gender / seat number / product / ... 让我们更轻松地在触摸屏设备上...
  • iOS 自定义日期选择器

    2016-01-18 16:18:10
    前言封装了一个日期选择器,解决两个问题: 1、点击textField,键盘弹出和日期选择器弹出的逻辑处理; 2、同一个界面需要多次用到日期选择器时,判断点击的textField;一、封装日期选择器类YCDatePickerView1、新建...
  • iOS 日期选择器 TDSemiModal ,TDSemiModal 在 iOS 上实现了半模态的日期选择器
  • 仿ios日期选择器

    千次阅读 2015-12-25 13:52:56
    主要是运用原生的Calendar日期类实现的 效果如下 //放在onCreateView 里 初始化获取  Calendar mycalendar = Calendar.getInstance(Locale.CHINA);  Date mydate = new Date();  mycalendar.setTime(mydate);
  • iOS 日期选择器 MZDayPicker ,MZDayPicker 是 iOS 上的一个用于选择日期的控件。
  • iOS开发底部弹出年月日选择器的使用代码,具体的样式代码请参考我对应写的博客空间,博客地址为:http://blog.csdn.net/sp_wei/article/details/77862694
  • 在android和ios上的flutter应用程序中显示时间和日期选择器
  • Android仿ios时间日期选择器

    千次阅读 2017-03-02 11:18:12
    1.使用开源控件: compile 'com.bigkoo:pickerview:2.1.1' 日期选择:private void timePicke(final EditText editText) { editText.setInputType(InputType.TYPE_NULL); final TimePickerView pvTime = new T
  • Android 仿iOS时间选择器自定义WheelView

    万次阅读 多人点赞 2016-03-24 18:01:54
    ios的自带时间选择器很好看,但是android的自带时间选择器就各不相同,有的看起来还可以,但是有的就其丑无比,网上仿ios的自定义时间选择器 基本都是WheelView,上效果图吧,这是我修改过的结果。   /** *...
  • 这是一个时间选择器,弥补系统默认的只能选择年月日功能,这里增加了只选择年和年月两种模式!
1 2 3 4 5 ... 20
收藏数 13,848
精华内容 5,539
热门标签
关键字:

ios日期选择器