【问题标题】:How to animate UIBarButtonItem to slide on the UIToolbar from the left?如何为 UIBarButtonItem 设置动画以从左侧在 UIToolbar 上滑动?
【发布时间】:2014-01-17 21:29:51
【问题描述】:

在我的 iOS 应用程序中,我有一个带有 UIToolbar 控件的媒体播放器。当我触摸播放器屏幕时,我想让 UIBarButtonItem 从左侧滑到 UIToolbar 上。

这是我尝试过的,它确实从左侧添加了 UIBarButtonItem,但没有动画部分。

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

非常感谢任何形式的帮助!

【问题讨论】:

    标签: ios ipad uibarbuttonitem uitoolbar


    【解决方案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 栏按钮项目并获取所有这些按钮的初始位置,然后拉动它们进入工具栏(和项目列表之外),为它们设置动画,然后将所有内容放回原处。 (简单,对吧?)祝你好运!

    【讨论】:

    • 谢谢!这是一个非常好的方法!我以类似的方式解决了这个问题。但是,我杀死了 UIToolbar 并构建了我自己的带有 UIButtons 的自定义工具栏......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    • 2012-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多