How to animate UIBarButtonItem to navigate the UIToolbar on the left?

In my iOS application, I have a media player with UIToolbar for controls. I want the UIBarButtonItem to shift to the left of the UIToolbar when I touch the player screen.

This is what I tried and it adds a UIBarButtonItem on the left, but there is no animation part.

  // create new button
  UIBarButtonItem* b = [[UIBarButtonItem alloc] initWithTitle:@"b"
                                                        style:UIBarButtonItemStyleBordered
                                                       target:self
                                                       action:nil];

  NSMutableArray* temp = [toolbar.items mutableCopy]; // store the items from UIToolbar

  NSMutableArray* newItems = [NSMutableArray arrayWithObject:b]; // add button to be on the left

  [newItems addObjectsFromArray:temp]; // add the "old" items

  [toolbar setItems:newItems animated:YES];

Any help is appreciated!

+4
source share
1 answer

I had a similar problem when a developer needs such animation in the navigation bar.

Assuming your application does not need other buttons to move, you can do it like this:

    // create a UIButton instead of a toolbar button
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"b" forState:UIControlStateNormal];

    // Save the items *before* adding to them
    NSArray *items = toolbar.items;

    // Create a placeholder view to put into the toolbar while animating
    UIView *placeholderView = [[UIView alloc] initWithFrame:button.bounds];
    placeholderView.backgroundColor = [UIColor clearColor];
    [toolbar setItems:[items arrayByAddingObject:[[UIBarButtonItem alloc] initWithCustomView:placeholderView]]
             animated:NO];

    // get the position that is calculated for the placeholderView which has been added to the toolbar
    CGRect finalFrame = [toolbar convertRect:placeholderView.bounds fromView:placeholderView];
    button.frame = CGRectMake(-1*button.bounds.size.width, finalFrame.origin.y, button.bounds.size.width, button.bounds.size.height);
    [toolbar addSubview:button];
    [UIView animateWithDuration:duration
                     animations:^{ button.frame = finalFrame; }
                     completion:^(BOOL finished) {
                         // swap the placeholderView with the button
                         [toolbar setItems:[items arrayByAddingObject:[[UIBarButtonItem alloc] initWithCustomView:button]]
                                  animated:NO];
                     }];

, b/c CustomView , ( ), , . (, ?) !

+1

All Articles