一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

iOS UIDatePicker+UIToolbar时间选择器实例

时间:2016-08-15 编辑:简简单单 来源:一聚教程网


简单的时间选择器,其实就是利用了UITextField的inputView属性。直接看代码:

#import "ViewController.h"
 
@interface ViewController (){
    UITextField *textFiled;
    NSString *timeStr;
}
 
@end
 
@implementation ViewController
 
- (void)viewDidLoad {
    [super viewDidLoad];
    textFiled = [[UITextField alloc] initWithFrame:CGRectMake(70, 80, 120, 30)];
    textFiled.layer.borderColor = [[UIColor grayColor]CGColor];
    textFiled.layer.border.0f;
    [self.view addSubview:textFiled];
    
    //添加一个时间选择器
    UIDatePicker *datePicker = [[UIDatePicker alloc]init];
    //设置只显示中文
    [datePicker setLocale:[NSLocale localeWithLocaleIdentifier:@"zh-CN"]];
    //添加滚动事件
    [datePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
    //设置只显示日期
    datePicker.datePickerMode = UIDatePickerModeDate;
    //当光标移动到文本框的时候,召唤时间选择器
    textFiled.inputView = datePicker;
    //创建工具条
    UIToolbar *toolbar = [[UIToolbar alloc]init];
    //设置工具条的颜色
    toolbar.barTintColor = [UIColor blackColor];
    //设置工具条的frame
    toolbar.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 35);
    
    //给工具条添加按钮
    UIBarButtonItem *item0 = [[UIBarButtonItem alloc]initWithTitle:nil style:UIBarButtonItemStylePlain target:self action:nil];
    
    UIBarButtonItem *item1 = [[UIBarButtonItem alloc]initWithTitle:nil style:UIBarButtonItemStylePlain target:self action:nil];
    
    UIBarButtonItem *item2 = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    
    UIBarButtonItem *item3 = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(click:)];
    
    toolbar.items = @[item0,item1,item2,item3];
    //设置文本输入框键盘的辅助视图
    textFiled.inputAccessoryView = toolbar;
}
 
#pragma mark - 时间选择
-(void)dateChanged:(UIDatePicker *)sender{
    NSDate *date = sender.date;
    
    NSDateFormatter *yearDateFormatter = [NSDateFormatter new];
    yearDateFormatter.dateFormat = @"yyyy";
    
    NSDateFormatter *monthDateFormatter = [NSDateFormatter new];
    monthDateFormatter.dateFormat = @"MM";
    
    NSDateFormatter *dayDateFormatter=[NSDateFormatter new];
    [dayDateFormatter setDateFormat:@"dd"];
    
    timeStr = [NSString stringWithFormat:@"%@-%@-%@",[yearDateFormatter stringFromDate:date],[monthDateFormatter stringFromDate:date],[dayDateFormatter stringFromDate:date]];
 
}
 
#pragma mark - 确定按钮点击
-(void)click:(UIButton *)sender
{
    NSLog(@"timeStr>=%@",timeStr);
    textFiled.text = timeStr;
    [textFiled resignFirstResponder];
}
 
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
 
@end

热门栏目