Search code examples
iosuiviewcontrollerdelegatesuidatepickeruipopover

uidatepicker in uipopover delegate


I am trying to insert a uipopover with uidatepicker in it with two buttons - Cancel and Done. I was able to design the layout using storyboard with the help of UIDatePicker in UIPopover and How can I show a UIDatePicker inside a Popover on iPad using StoryBoard?

But, I am not able to get the date from uidatepicker to uiviewcontroller when Done button is pressed. I am new to ios programming and i find delegate methods very confusing. Could somebody shed some light? Help much appreciated. Thank you :)

enter image description here


Solution

  • You are absolutely correct one way to get the value in view controller is to implement delegate functions. These are very easy if you understand at the technical level. I will try to explain it here.

    you have to define the protocol in the datePickerViewcontrollerClass.h like this

    @protocol TimePopupViewControllerDelegate <NSObject> 
    -(void)returnSelectedDate:(NSDate*)date;
    @end
    

    and create a instance of 'id' type for passing the reference of mainViewController like this.

    @property (nonatomic, assign) id < TimePopupViewControllerDelegate > delegate;

    in MainViewController.m where you are creating instance of datePickerViewcontrollerClass, you have to set the delegate like this

    datePickerViewcontrollerClass *myViewControllerForPopover =[[datePickerViewcontrollerClass alloc] init];
    myViewControllerForPopover.delegate = self;
    

    in the method where you getting the date from picker in datePickerViewcontrollerClass.m class you have to pass it to main class using delegate.

    -(void)viewDidDisappear:(BOOL)animated{
         [_delegate returnSelectedDate:datepicker.date];
    [super viewWillDisappear:animated];
    

    }

    you can write this in any method I have written in ViewWillDisappear or any other method.

    After this in MainViewController this method get called and you can retrieve the selected date

    -(void)returnSelectedDate:(NSDate *)date{
    }
    

    Technically you are passing the referece of mainViewController instance to your datePickerViewcontrollerClass and calling the methods on mainViewController from datePickerViewcontrollerClass I hope I will be able to explain it clearly if you still any doubt you can comment.