2010-01-18 34 views
0

是否有任何方法將像Apple旋轉設備這樣的動畫圖像設置爲UIBarButtonItem?iPhone SDK:將動畫加載(齒輪)圖像設置爲UIBarButtonItem

我已經試過這行代碼,但動畫GIF圖像不會玩:

myButton.image = [UIImage imageNamed:@"spinningGear.gif"]; 
+0

的尺寸上略有錯了 - 雖然技術本身是好的 - 請參閱下面的修正 – Adam 2010-07-29 12:36:46

回答

2

嘗試創建一個UIActivityIndicatorView並將其與-[UIBarButtonItem initWithCustomView:]分配給您的按鈕。

+0

這是行不通的。我不知道你在哪裏嘗試過 - 在iOS 3中不起作用,並且似乎不適用於iOS 4或者 – Adam 2010-07-29 12:37:58

0

我不認爲用UIBarButtonItem是可能的。

您可能想要使用customView作爲該屬性(),並使用UIImageView作爲該視圖。這仍然不會動畫GIF的「開箱即用」(只是檢查)。

如果你這樣做,你有兩個選擇:

  • 使用animatedImages從UIImageView類,並使用單獨的圖像,每幀(寫出頭 - 代碼可能有一些錯誤):

 
NSMutableArray * imgs = [NSMutableArray array]; 
for(int i = 0; i < NUMBER_OF_FRAMES; i++) { 
    [imgs addObject: [UIImage imageNamed: [NSString stingWithFormat: @"anim%d.png", i]]]; 
} 
UIImageView * imgview = [[UIImageView alloc] init]; 
imgview.animatedImages = imgs; 
[imgview startAnimating]; 

0

我發現,這條線是不正確的:

[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)]; 

...從蘋果默認的刷新按鈕的實際尺寸稍有不同。如果您有其他項目在該工具欄上進行自動佈局,則需要正確設置尺寸。

不幸的是,蘋果提供沒有API找出大小。通過試驗和錯誤,看來這是正確的:

[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 28, 28)]; 
+0

您也可以'sizeToFit'然後查看'bounds'。 – kevboh 2012-02-23 20:57:05

0

我通過設置的UIBarButtonItem到一個UIButton的customView與圖標圖像,再加入UIActivityIndi​​cator作爲的UIButton的子視圖這樣做。

要設置它,我只需將UIButton拖到Interface Builder中的UIBarButtonItem(您也可以在代碼中執行此操作)。然後,以顯示活動的指標:

UIButton *customButton = (UIButton *)self.refreshButton.customView; 
[customButton setImage:nil forState:UIControlStateNormal]; 
[customButton removeTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside]; 
[customButton addTarget:self action:@selector(altButtonAction) forControlEvents:UIControlEventTouchUpInside]; 
self.activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite]; 
self.activityIndicator.frame = CGRectMake(round((customButton.frame.size.width - 25)/2), round((customButton.frame.size.height - 25)/2), 25, 25); 
self.activityIndicator.userInteractionEnabled = FALSE; // this allows the button to remain tappable 
[customButton addSubview:self.activityIndicator]; 
[self.activityIndicator startAnimating]; 

,並返回到默認的按鈕狀態:

UIButton *customButton = (UIButton *)self.refreshButton.customView; 
[customButton setImage:[UIImage imageNamed:@"IconRefresh"] forState:UIControlStateNormal]; 
[customButton removeTarget:self action:@selector(altButtonAction) forControlEvents:UIControlEventTouchUpInside]; 
[customButton addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside]; 
[self.activityIndicator removeFromSuperview]; 
[self.activityIndicator release]; 

的幾個注意事項:

  1. 如果你不想更改按鈕當它處於「活動」狀態時,您可以刪除addTarget和removeTarget行。
  2. 如果您不希望按鈕處於「活動」狀態時可點擊,您可以省略活動指示器的userInteractionEnabled行(或刪除目標並重新添加它)。
  3. 具有customView的UIBarButtonItem不會顯示按鈕邊框。如果你想要這個邊框,你必須製作自己的圖像並將其添加爲UIButton的背景圖像。