点击UITextField弹出日期选择器 iOS

时间:2015-05-26 16:00:10   收藏:0   阅读:9806

在.h文件里加入UITextFieldDelegate

@property(nonatomic,retain) UITextField * phoneNumberTextField;
@property(retain,nonatomic)UIDatePicker *datePicker;

在.m文件viewdidload里   

    UIDatePicker *datePicker=[[UIDatePicker alloc]initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width, 162)];

    datePicker.datePickerMode=UIDatePickerModeDate;

    datePicker.date=[NSDate date];

    [self.view addSubview: datePicker];

      self.datePicker=datePicker;

    [self.datePicker addTarget:self action:@selector(selectDate:) forControlEvents:      UIControlEventValueChanged];


    UITextField * aPhoneNumberTextfield = [[UITextField alloc] initWithFrame:CGRectMake(85, 210, 80, 30)];

    aPhoneNumberTextfield.backgroundColor = [UIColor whiteColor];

    aPhoneNumberTextfield.placeholder = @"请选择";

    aPhoneNumberTextfield.clearButtonMode = UITextFieldViewModeAlways;

    aPhoneNumberTextfield.autocapitalizationType = UITextAutocapitalizationTypeNone;

    aPhoneNumberTextfield.borderStyle = UITextBorderStyleNone;

    aPhoneNumberTextfield.delegate = self;

    [self.scrollView addSubview:aPhoneNumberTextfield];

    self.phoneNumberTextField = aPhoneNumberTextfield;

  

然后

-(void)selectDate:(id)sender

{

 

    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];

    [outputFormatter setDateFormat:@"MM-dd"];

    NSString *str=[outputFormatter stringFromDate:self.datePicker.date];

    self.phoneNumberTextField.text=str;

    

    NSLog(@"%@",self.datePicker.date);

    NSLog(@"%@",str);

}
下面为了防止UItextfield弹出键盘

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{

    

    if (textField==self.phoneNumberTextField) {

        self.phoneNumberTextField.inputView=self.datePicker;

    } 

    

    return YES;

} 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!