Domanda

In my iOS app I have a media player with UIToolbar for the controls. I want to make UIBarButtonItem slide from the left onto the UIToolbar as I touch on the player screen.

This is what I've tried, and it does add the UIBarButtonItem from 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 kind of help is highly appreciated!

È stato utile?

Soluzione

I had a similar issue where the designer wanted that kind of animation in a navbar.

Assuming that your app does not need the other buttons to move, then 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];
                     }];

If your app does need to move the other buttons, then it's a bit trickier b/c you have to use only customView bar button items and get the initial position of all of them, pull them into the toolbar (and out of the list of items), animate them, and then put everything back. (Easy, right?) Good luck!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top