Search code examples
iosuipickerview

programmatically adding button to UIToolbar


I am programmatically creating a UIToolbar with this code:

pickerTB = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
[self.view addSubview:pickerTB];

How do i add one single button to it? It needs to say "Done" and the button must be able to call a method later on.


Solution

  • Try this, If you want to add DONE button on right side of uitoolbar then add flexible button before done button

     UIBarButtonItem *flexButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
     UIBarButtonItem *doneButton =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneButton)];
    
     NSArray *itemsArray = [NSArray arrayWithObjects:flexButton, doneButton, nil];
    
    
     [toolbar setItems:itemsArray];
    
    -(void)doneButton
    {
    }
    

    // change toolbar style

     [toolbar setBarStyle:UIBarStyleBlackTranslucent];
    

    //change bar button color

    [doneButton setTintColor:[UIColor blackColor]];