如何使UIBarButtonItem从左侧滑动到UIToolbar上以实现动画效果?

4
在我的iOS应用程序中,我有一个带有UIToolbar控件的媒体播放器。我想让UIBarButtonItem从左侧滑动到UIToolbar上,当我触摸播放器屏幕时。
这是我尝试过的方法,它确实将UIBarButtonItem从左侧添加到了UIToolbar上,但没有动画效果。
  // 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];

非常感谢您的帮助!

1个回答

1

我曾遇到类似问题,设计师希望在导航栏中使用这种类型的动画。

假设你的应用程序不需要其他按钮移动,那么你可以这样做:

    // 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];
                     }];

如果您的应用程序确实需要移动其他按钮,那么情况就有点棘手,因为您必须仅使用customView bar按钮项并获取所有按钮的初始位置,将它们拉入工具栏(而不是项目列表),对其进行动画处理,然后将所有内容放回。(很容易,对吧?)祝好运!

谢谢!这是一个非常好的方法!我用类似的方式解决了这个问题。不过,我放弃了UIToolbar并建立了自己的自定义工具栏,并在上面添加了UIButtons... - Eugene Gordin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接