I know UIPickerViews use a didSelectRow method to update labels etc when a row is selected.
I have a UIDatePicker that updates a label when a row is selected and done button is pressed, but I also want a UILabel that updates with 开发者_开发技巧each selection, so its live updating as the user changes the date. I can't find any method such as didSelectRow for the date picker though. How is this possible?
- (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;
}
UIDatePicker is a UIControl, so use
[picker addTarget:yourController action:@selector(yourAction:) forControlEvents:UIControlEventValueChanged];
to send a message to your controller. The controller can then get the state of the date picker and update the label.
If your picker and your label are both outlets in the same class, in viewDidLoad:
[self.picker addTarget:self action:@selector(updateLabelFromPicker:) forControlEvents:UIControlEventValueChanged];
Then create updateLabelFromPicker:
- (IBAction)updateLabelFromPicker:(id)sender {
self.label.text = [self.dateFormatter stringFromDate:self.picker.date];
}
You'll want an NSDateFormatter to make the date pretty.
A date picker does things a little differently. From the documentation:
When properly configured, a UIDatePicker object sends an action message when a user finishes rotating one of the wheels to change the date or time; the associated control event is UIControlEventValueChanged.
Because a UIDatePicker inherits from UIControl, you have access to all the various touch events you'd expect (TouchUpInside, etc).
Swift 3/4
func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int)
{
println("\(courseCatalog[row])")
yourlabelname.text=courseCatalog[row]
}
精彩评论