2010-06-03 4 views
37

Я хочу заменить мой UIBarButtonItem (используется для обновления) с помощью UIActivityIndicatorView и, когда обновление закончено, я хочу вернуться к кнопке обновления и удалить UIActivityIndicatorView.Замените UIBarButtonItem на UIActivityIndicatorView

ответ

48

Просто создать две разные UIBarButtonItem s

Один за индикатором активности, а другой для нормального UIBarButtonItem.

UIActivityIndicatorView * activityView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 25, 25)]; 
[activityView sizeToFit]; 
[activityView setAutoresizingMask:(UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin)]; 
UIBarButtonItem *loadingView = [[UIBarButtonItem alloc] initWithCustomView:activityView]; 
[self.navigationItem setRightBarButtonItem:loadingView]; 
[loadingView release]; 
[activityView release]; 

UIBarButtonItem * normalButton = [[UIBarButtonItem alloc] initWithTitle...]; 
[self.navigationItem setRightBarButtonItem:normalButton]; 
[normalButton release]; 

Если вы хотите поменять их, просто переназначить rightBarButtonItem в зависимости от того.

+0

Я еще маленький вопрос. С этой реализацией я могу назвать beginAnimation и stopAnimation на UIActivityIndicatorView? Спасибо – Luca

+0

Вы можете создать свойство для UIActivityIndicatorView. –

+0

Большое спасибо – Luca

10

Вот что работает для меня:

- (void) rightItemButtonWithActivityIndicator 
{ 
    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)]; 
    [activityIndicator startAnimating]; 
    UIBarButtonItem *activityItem = [[UIBarButtonItem alloc] initWithCustomView:activityIndicator]; 
    [activityIndicator release]; 
    self.navigationItem.rightBarButtonItem = activityItem; 
    [activityItem release]; 
} 
2

Я использовал подобную технику для обновления кнопки в UIToolbar когда UIWebView является перегрузка (как это не представляется возможным, чтобы показать/скрыть отдельные панели кнопки). В этом случае вам нужно поменять все элементы в UIToolbar.

@property (strong, nonatomic) IBOutlet UIBarButtonItem *refreshBarButton; 

@property (nonatomic, strong) UIActivityIndicatorView *activityView; 
@property (nonatomic, strong) UIBarButtonItem *activityBarButton; 

@property (strong, nonatomic) IBOutlet UIToolbar *toolbar; 
@property (strong, nonatomic) IBOutlet UIBarButtonItem *backBarButton; 
@property (strong, nonatomic) IBOutlet UIBarButtonItem *refreshBarButton; 
@property (strong, nonatomic) IBOutlet UIBarButtonItem *forwardBarButton; 

#pragma mark - UIWebViewDelegate 
-(void)webViewDidFinishLoad:(UIWebView *)webView{ 
    [self updateButtons]; 
} 

-(void)webViewDidStartLoad:(UIWebView *)webView{ 
    [self updateButtons]; 
} 

-(void)updateButtons{ 
    /* 
    It's not possible to show/hide bar button items so we need to do swap out the toolbar items in order to show the progress view 
    */ 

    //Initialise the activity view 
    if (self.activityBarButton == nil){ 
     self.activityView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)]; 
     self.activityBarButton = [[UIBarButtonItem alloc] initWithCustomView:self.activityView]; 
     self.activityBarButton.enabled = NO; 
    } 


    NSMutableArray *toolbarItems = [[NSMutableArray alloc] initWithArray:self.toolbar.items]; 

    if ([self.webview isLoading]){ 
     //Replace refresh button with loading spinner 
     [toolbarItems replaceObjectAtIndex:[toolbarItems indexOfObject:self.refreshBarButton] 
           withObject:self.activityBarButton]; 

     //Animate the loading spinner 
     [self.activityView startAnimating]; 
    } 
    else{ 
     //Replace loading spinner with refresh button 
     [toolbarItems replaceObjectAtIndex:[toolbarItems indexOfObject:self.activityBarButton] 
           withObject:self.refreshBarButton]; 

     [self.activityView stopAnimating]; 
    } 

    //Set the toolbar items 
    [self.toolbar setItems:toolbarItems]; 


    //Update other buttons 
    self.backBarButton.enabled = [self.webview canGoBack]; 
    self.forwardBarButton.enabled = [self.webview canGoForward]; 
} 
7

Я пытался сделать то же самое, и я думал, что установка self.navigationItem.rightBarButtonItem не работает, потому что индикатор активности не будет отображаться. Оказывается, он работает нормально, я просто не мог этого видеть, потому что у меня есть белая панель навигации, а стиль UIActivityIndicatorView по умолчанию также белый. Так было там, но невидимо. С серым стилем я теперь вижу это.

UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; 

(Duh.)

Смежные вопросы