关于日期选择器iOS

时间:2013-05-11 08:29:51

标签: ios objective-c

我需要一个日期选择器出现在文本字段的水龙头上。我已经成功了。现在我有两个问题: 它显示日期和时间。我只需要约会。 如果我在后台的某个地方点击,我需要选择器消失。

我的代码是:

- (void)viewDidLoad
{

    [super viewDidLoad];
    UIDatePicker *datePicker = [[UIDatePicker alloc]init];
    datePicker.datePickerMode = UIDatePickerModeDate;

    [datePicker setDate:[NSDate date]];

     [datePicker addTarget:self action:@selector(updateTextField:) forControlEvents:UIControlEventValueChanged];
     [self.text1 setInputView:datePicker];
        // Do any additional setup after loading the view, typically from a nib.
}
-(void)updateTextField:(id)sender
{
    UIDatePicker *picker = (UIDatePicker*)self.text1.inputView;
        self.text1.text = [NSString stringWithFormat:@"%@",picker.date];
}

我使用了datePicker.datePickerMode = UIDatePickerModeDate;,但我仍然有时间。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];
NSString *yeardate = [dateFormat stringFromDate:[NSDate date]];
//Set this yeardate to your datepicker.
[datePicker setDate:[dateFormat dateFromString:yeardate]];

希望这有帮助。

答案 1 :(得分:0)

您正在为textField分配日期说明,使用NSDateFormatter从datePicker转换日期。

要解雇,您可以在视图中添加tapGestureRecognizer,也可以将accessoryInputView添加到textField

- (void)viewDidLoad
{
    [super viewDidLoad];

    UITapGestureRecognizer *tapRecognizer  = [UITapGestureRecognizer new];
    [tapRecognizer addTarget:self action:@selector(didTapView:)];
    [self.view addGestureRecognizer:tapRecognizer];

}

- (void)didTapView:(UITapGestureRecognizer *)tapRecognizer{
    [self.textField resignFirstResponder];
}

OR

- (void)viewDidLoad
{
    [super viewDidLoad];

     UIToolbar *toolbar =[[UIToolbar alloc]initWithFrame:CGRectMake(0,0, self.view.frame.size.width,44)];
    toolbar.barStyle =UIBarStyleBlackOpaque;

    UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
                                                                                 target:self
                                                                                 action:@selector(cancelButtonPressed:)];

    UIBarButtonItem *flexibleSpace =[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                                 target:self
                                                                                 action:nil];

    UIBarButtonItem *doneButton =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
                                                                               target:self
                                                                               action:@selector(doneButtonPressed:)];
    [toolbar setItems:@[cancelButton,flexibleSpace, doneButton]];

    _activeTextField.inputAccessoryView = toolbar;

}