rgamber rgamber - 1 year ago 58
Swift Question

Change value of a uidatepicker from a button on the InputAccessoryView

I have a

which is created programmatically (as the first-responder) when user taps a text-field on my view. This happens inside a for-loop, so I don't have the reference to this picker in my code. I also have a toolbar on top of the picker which is added as an
to the picker. I have a Done button which resigns the first-responder. So far so good.

I want to add another button on the toolbar besides the Done button which will change the value of the picker. There is no
which will let me track the active picker.

I can always define class variables for each of my picker and thus save the references manually. But is there an easy way to do this where I can access the
from the


this in some.h File

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

     IBOutlet UIDatePicker *picker1;
     IBOutlet UITextField *txtFld;

@property (nonatomic, retain) UIToolbar *keyboardToolbar;


In some.m file

- (void)viewDidLoad
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
 picker1=[[UIDatePicker alloc] initWithFrame:CGRectMake(0, 0, 320, 300)];//frames are just for demo
 [txtFld setInputView:picker1];

- (void)keyboardWillShow:(NSNotification *)notification
    if(keyboardToolbar == nil) {
        keyboardToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 410, 320, 44)] ;
        [keyboardToolbar setBarStyle:UIBarStyleBlackTranslucent];
        [keyboardToolbar sizeToFit];

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.4];

        UIBarButtonItem *flexButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];

        UIBarButtonItem *doneButton1 =[[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(resignKeyboard)];
        NSArray *itemsArray = [NSArray arrayWithObjects:flexButton,doneButton1, nil];

        [keyboardToolbar setItems:itemsArray];

        [txtFld setInputAccessoryView:keyboardToolbar];
        [self.view addSubview:keyboardToolbar];
        [UIView commitAnimations];

-(void)resignKeyboard {

    [keyboardToolbar removeFromSuperview];
    [txtFld resignFirstResponder];
///do nescessary date calculation here