2014-01-17 36 views
4

在我的iOS應用程序中,我有一個UIToolbar控件的媒體播放器。我想讓UIBarButtonItem從左側滑入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]; 

任何形式的幫助,高度讚賞!

回答

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

如果您的應用程序需要移動其他按鈕,那麼它是一個有點棘手b/c只需使用customView欄按鈕項目並獲取所有這些項目的初始位置,將它們拖入工具欄(並從項目列表中除外),爲它們設置動畫,然後將所有內容都放回原處。 (簡單,對吧?)祝你好運!

+0

謝謝!這是一個非常好的方法!我以類似的方式解決了這個問題。但是,我殺死了UIToolbar並在其上創建了自己的帶有UIButton的自定義工具欄... –