xcode 如何更改标签上的日期选择器选定值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13044724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to change datepicker selected value on label
提问by Johny Bravo
i wanted to display selected date from datepicker on label but the label just show me the current date of day it not show me the date which i have selected from the datepicker this is the code kindly tell me how i can change text label with the randomly selected date from the datepicker
我想在标签上显示从日期选择器中选择的日期,但标签只向我显示当前日期它没有向我显示我从日期选择器中选择的日期这是代码,请告诉我如何使用随机更改文本标签从日期选择器中选择的日期
#import "ViewController.h"
@implementation ViewController
@synthesize datepicker,mylabel;
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
NSDate *chosen = datepicker.date;
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
formatter.dateStyle = NSDateFormatterMediumStyle;
mylabel.text = [formatter stringFromDate:chosen];
[formatter release];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
@end
回答by NANNAV
// code for Date picker for current date
datepicker=[[UIDatePicker alloc]initWithFrame:CGRectMake(0, 200, 320, 150)];
//[self.view addSubview:datepicker];
datepicker.date = [NSDate date];
datepicker.datePickerMode=UIDatePickerModeDate;
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.timeStyle = NSDateFormatterNoStyle;
label.text=[NSString stringWithFormat:@"%@",
[df stringFromDate:[NSDate date]]];
df.dateFormat = @"yyyy-MM-dd";
// set action for date picker
[datepicker addTarget:self action:@selector(DateChange:)
forControlEvents:UIControlEventValueChanged];
//method for change date
- (void)DateChange:(id)sender
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
label.text = [dateFormatter stringFromDate:datepicker.date];
date.text=strDate;
}