UIDatePicker 作为 inputView [英] UIDatePicker as inputView

查看:76
本文介绍了UIDatePicker 作为 inputView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 UIDatePicker 作为 inputView 有两个问题.

1:当我在 datePicker 中选择April 17 9 00 PM"时,
dateTextField 输出2014-04-107 21:00:00".

I have two problems at UIDatePicker as inputView.

1: When I select "April 17 9 00 PM" in datePicker,
dateTextField outputs "2014-04-107 21:00:00".

2:我所在国家/地区的 UTC 是 +0900.
但是,NSLog 输出2014-04-17 12:00:00 +0000".

我该如何解决这些问题?

2: UTC of My country is +0900.
But, NSLog outputs "2014-04-17 12:00:00 +0000".

How do I fix these problems?

@property IBOutlet UITextField* dateTextField;
@property IBOutlet UIDatePicker* datePicker;
@property UIToolbar* toolBar;

- (void)viewDidLoad
{
    self.datePicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(0, 600, 320, 216)];
    [self.view addSubview:self.datePicker];
    self.toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, -40, 320, 40)];
    self.toolBar.barStyle = UIBarStyleBlackOpaque;
    UIBarButtonItem* doneButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(dateTextFieldShouldReturn)];
    NSArray* finishBarItems = [NSArray arrayWithObjects:doneButton, nil];
    [self.toolBar setItems:finishBarItems animated:YES];

    self.dateTextField = [[UITextField alloc]initWithFrame:CGRectMake(40, 293, 250, 30)];
    self.dateTextField.delegate = self;
    self.dateTextField.inputView = self.datePicker;
    self.dateTextField.inputAccessoryView = self.toolBar;
    [myScrollView addSubview:self.dateTextField];
}

- (void)dateTextFieldShouldReturn
{
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-DD HH:mm:ss"];
    NSString* dateString = [formatter stringFromDate:self.datePicker.date];
    [self.dateTextField setText:dateString];
    [self.dateTextField resignFirstResponder];

    NSDate* date = [formatter dateFromString:self.dateTextField.text];
    NSLog(@"%@", date);
}

推荐答案

像这样对我有用:

- (void)dateTextFieldShouldReturn
{
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];

    [formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"]];
    [formatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss zzz"];


    NSString* dateString = [formatter stringFromDate:self.datePicker.date];
    [self.dateTextField setText:dateString];
    [self.dateTextField resignFirstResponder];

    NSDate* date = [formatter dateFromString:self.dateTextField.text];
    NSLog(@"%@", date);
}

这篇关于UIDatePicker 作为 inputView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆