簡單的時間選擇器,其實就是利用了UITextField的inputView屬性。直接看代碼:
#import "ViewController.h"
@interface ViewController ()<UITextFieldDelegate>{
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.borderWidth = 1.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