Question

Can someone tell me why my button is on the left side instead of the right? I would like it on the right. Thanks for any help you can give!

- (IBAction)getSelection:(id)sender {

    if(self.pickerShown == NO){

        self.slidePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0,0, 320, 216)];
        self.slidePicker.datePickerMode = UIDatePickerModeTime;
        self.slidePicker.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:self.slidePicker];

        //make done button
        self.toolBar= [[UIToolbar alloc] initWithFrame:CGRectMake(0,0,320,44)];
        self.toolBar.barTintColor = [UIColor whiteColor];
        self.barButtonDone = [[UIBarButtonItem alloc] initWithTitle:@"Done"
                                                              style:UIBarButtonItemStylePlain target:self
                                                             action:@selector(testButton)];

        self.toolBar.items = [[NSArray alloc] initWithObjects:self.barButtonDone,nil];
        self.navigationItem.rightBarButtonItem = self.barButtonDone;
        self.barButtonDone.tintColor=[UIColor blackColor];
        self.pickerShown = YES;
        [self.view addSubview:self.toolBar];
    }
    else {
        return;
    }
}
Was it helpful?

Solution

You need to add:

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

And change:

self.toolBar.items = [[NSArray alloc] initWithObjects: flexSpace, self.barButtonDone,nil];

I thing that you can:

//self.navigationItem.rightBarButtonItem = self.barButtonDone;

Information:

UIBarButtonSystemItemFlexibleSpace is a blank space to add between other items. The space is distributed equally between the other items. Other item properties are ignored when this value is set.

Apple documentation: UIBarButtonItem Class Reference

Also, you have the Flexible Space Bar Button Item in Xcode Interface Builder:

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top