UIDatePicker DidSelectRow方法?

时间:2011-04-21 19:19:17

标签: iphone objective-c cocoa-touch

我知道UIPickerViews在选择行时会使用didSelectRow方法更新标签等。

我有一个UIDatePicker,当选择一行并按下完成按钮时更新标签,但我还想要一个随每个选择更新的UILabel,因此当用户更改日期时它会进行实时更新。我找不到日期选择器的任何方法,例如didSelectRow。这怎么可能?

- (IBAction)dateButtonPressed
{
    [dateView setFrame:CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, self.view.frame.size.height)];
    [self.view addSubview:dateView];

    UIBarButtonItem *acceptButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(dismssPickerChangeDate)];
    self.navigationItem.rightBarButtonItem = acceptButton;
    [acceptButton release];

    UIBarButtonItem *cancelButton1 = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(dismssPickerCancel)];
    self.navigationItem.leftBarButtonItem = cancelButton1;
    [cancelButton1 release];

    self.navigationItem.title = @"Select Date";
    self.navigationItem.hidesBackButton = YES;
    [UIView animateWithDuration:.5 animations:^{
        [dateView setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    }];
    NSDate *myDate = picker.date;

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
    //NSDate *date = [NSDate date]; 
    [dateFormatter setDateFormat:@"MMM d y"]; 
    NSString *dateString = [dateFormatter stringFromDate:myDate]; 
    NSLog(@"New Date is = %@",dateString);
    dateLabel.text = dateString;
}

3 个答案:

答案 0 :(得分:25)

UIDatePicker是一个UIControl,所以使用

[picker addTarget:yourController action:@selector(yourAction:) forControlEvents:UIControlEventValueChanged];

向您的控制器发送消息。然后,控制器可以获取日期选择器的状态并更新标签。

如果你的选择器和你的标签都是同一类中的出口,那么在viewDidLoad中:

[self.picker addTarget:self action:@selector(updateLabelFromPicker:) forControlEvents:UIControlEventValueChanged];

然后创建updateLabelFromPicker:

- (IBAction)updateLabelFromPicker:(id)sender {
    self.label.text = [self.dateFormatter stringFromDate:self.picker.date];    
}

你需要一个NSDateFormatter来使日期漂亮。

答案 1 :(得分:1)

日期选择器的做法略有不同。来自文档:

  

正确配置后,当用户完成其中一个轮子的旋转以更改日期或时间时,UIDatePicker对象会发送一条操作消息;关联的控件事件是UIControlEventValueChanged。

因为UIDatePicker继承自UIControl,所以您可以访问您期望的所有各种触摸事件(TouchUpInside等)。

答案 2 :(得分:0)

迅速3/4

func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int)
 {
   println("\(courseCatalog[row])")
    yourlabelname.text=courseCatalog[row]

}