// 初始化一个日期选择控件(不用指定宽高)
UIDatePicker *picker = [[[UIDatePicker alloc] init] autorelease];
// 设置显示中文
picker.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"] autorelease];
// 只显示年月日
picker.datePickerMode = UIDatePickerModeDate;
// 添加值改变的监听器
[picker addTarget:self action:@selector(birthdayChange:) forControlEvents:UIControlEventValueChanged];
self.birthday.inputView = picker;
#pragma mark 监听日期选择控件的改变
- (void)birthdayChange:(UIDatePicker *)picker {
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
formatter.dateFormat = @"yyyy-MM-dd";
self.birthday.text = [formatter stringFromDate:picker.date];
}
#pragma mark 返回NO代表不允许手动改变文本框的文本
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// 只有生日和性别才不允许修改文字
return !(textField == self.birthday || textField == self.sex);
}