Apple 回転ギアのようなアニメーション画像を UIBarButtonItem に設定する方法はありますか?
このコード行を試しましたが、アニメーション gif 画像が再生されません:
myButton.image = [UIImage imageNamed:@"spinningGear.gif"];
Apple 回転ギアのようなアニメーション画像を UIBarButtonItem に設定する方法はありますか?
このコード行を試しましたが、アニメーション gif 画像が再生されません:
myButton.image = [UIImage imageNamed:@"spinningGear.gif"];
を作成し、UIActivityIndicatorView
でボタンに割り当ててみてください-[UIBarButtonItem initWithCustomView:]
。
この行が正しくないことがわかりました。
[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
...Appleのデフォルトの[更新]ボタンの実際のサイズは少し異なります。そのツールバーで自動レイアウトを実行している他のアイテムがある場合は、適切なサイズを取得する必要があります。
残念ながら、Appleはサイズを見つけるためのAPIを提供していません。試行錯誤により、これは正しいようです。
[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 28, 28)];
これを行うには、UIBarButtonItemのcustomViewをアイコン画像付きのUIButtonに設定し、UIActivityIndicatorを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];
いくつかの注意:
UIBarButtonItem ではそれが可能だとは思いません。
customView
そのために(プロパティまたはinitWithCustomView
)使用UIImageView
し、そのビューとして使用することをお勧めします。それはまだgifの「箱から出して」(ちょうどチェックされた)アニメーション化されません。
その場合、次の 2 つのオプションがあります。
animatedImages
し、フレームごとに個別の画像を使用します (頭から書き出す - コードにエラーがある可能性があります)。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];
UIImageView
または、ここから gif 画像を作成するクラスを使用しますhttp://blog.stijnspijker.nl/2009/07/animated-and-transparent-gifs-for-iphone-made-easy