iOS - 删除以编程方式添加的子视图和标签中的打印日期

时间:2013-01-18 05:54:45

标签: iphone ios datepicker

我需要一些与iOS应用相关的帮助

点击按钮我以编程方式添加了DatePicker,现在我无法删除视图这是我的代码

我还尝试将日期放在标签dateLabel中,但它显示了一些运行时错误,因为它不是字符串格式我尝试了一些其他方法,如NSDateFormatter,但我没有得到正确的结果

-(IBAction)date:(id)sender{

    UIDatePicker *datePicker=[[UIDatePicker alloc]initWithFrame:CGRectMake(420, 320, 300, 500)];

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

    [self.view addSubview:datePicker];

    NSData *date=[datePicker date];
    NSLog(@"%@",date);
    dateLabel.text=date;
}

-(void)Pick:(id)sender{

    [datePicker removeFromSuperview];
}

3 个答案:

答案 0 :(得分:1)

这样做

-(IBAction)date:(id)sender
{
   datePicker=[[UIDatePicker alloc]initWithFrame:CGRectMake(420, 320, 300, 500)];
   [datePicker addTarget:self action:@selector(Pick:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:datePicker];
}

-(void)Pick:(id)sender
  {
     NSDateFormatter *df = [[NSDateFormatter alloc] init];
    df.dateStyle = kCFDateFormatterShortStyle;
     label.text=[NSString stringWithFormat:@"%@",
                     [df stringFromDate:datePicker.date]];
     [df release];
   [datePicker removeFromSuperview];
    datePicker=nil;
  }

答案 1 :(得分:0)

试试这个

在.h

中声明你的日期选择器
UIDatePicker *datePicker;

然后

-(IBAction)date:(id)sender
{
   datePicker=[[UIDatePicker alloc]initWithFrame:CGRectMake(420, 320, 300, 500)];
   [datePicker addTarget:self action:@selector(Pick:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:datePicker];
}

-(void)Pick:(id)sender
  {
     NSDate *date=[datePicker date];
     NSDateFormatter *dateformatter = [[NSDateFormatter alloc]init];
    [dateformatter setDateFormat:@"YYYY-MM-DD"];
    NSString *dateSTr = [dateformatter stringFromDate:date];
    NSLog(@"%@",dateSTr);
    dateLabel.text=date;
   [datePicker removeFromSuperview];
  }

答案 2 :(得分:0)

您将UIDatePicker *datePicker声明为本地变量。

只能在声明的函数(-(IBAction)date:(id)sender)中访问它。

您需要全局声明它以便在其他函数中使用它。

下的.m文件中声明该变量
@interface className()
  @property(nonatomic, strong) UIDatePicker *datePicker;
@end