/** * 创建时间选择器 */ - (void)createPickerView { self.datePicker = [[UIDatePicker alloc] init]; _datePicker.backgroundColor = [UIColor whiteColor]; // 设置只显示中文 [_datePicker setLocale:[NSLocale localeWithLocaleIdentifier:@"zh-CN"]]; // 设置只显示日期 _datePicker.datePickerMode = UIDatePickerModeDate; // 当光标移动到文本框时, 召出时间选择器 self.birthTextField.inputView = _datePicker; // 创建工具条 UIToolbar *toolBar = [[UIToolbar alloc] init];// 设置背景色 toolBar.barTintColor = [UIColor whiteColor]; toolBar.frame = CGRectMake(0, 0, SCREEN_WIDTH, 30); // 给工具条添加按钮 UIBarButtonItem *cancleItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancel)]; UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil]; // 设置UIBarButtonSystemItemFixedSpace的宽度 spaceItem.width = SCREEN_WIDTH - 100; UIBarButtonItem *sureItem = [[UIBarButtonItem alloc] initWithTitle:@"确认" style:UIBarButtonItemStylePlain target:self action:@selector(sure)]; // 设置字体颜色 toolBar.tintColor = [UIColor redColor]; toolBar.items = @[cancleItem, spaceItem, sureItem]; // 设置文本输入框键盘的辅助视图 self.birthTextField.inputAccessoryView = toolBar; } /** * 点击取消按钮 * * @param datePicker */ - (void)cancel { } /** * 点击确定按钮 * * @param datePicker */ - (void)sure { NSString *date = [NSString stringWithFormat:@"%@", _datePicker.date]; NSString *birth = [date substringToIndex:10]; self.birthTextField.text = birth; [_birthTextField resignFirstResponder]; }
效果如下:
时间: 2024-11-13 07:56:57