有没有办法将像 Apple 旋转齿轮这样的动画图像设置为 UIBarButtonItem?
我试过这行代码,但动画 gif 图像无法播放:
myButton.image = [UIImage imageNamed:@"spinningGear.gif"];
有没有办法将像 Apple 旋转齿轮这样的动画图像设置为 UIBarButtonItem?
我试过这行代码,但动画 gif 图像无法播放:
myButton.image = [UIImage imageNamed:@"spinningGear.gif"];
尝试创建 aUIActivityIndicatorView
并将其分配给您的按钮-[UIBarButtonItem initWithCustomView:]
。
我认为 UIBarButtonItem 不可能。
您可能希望customView
用于该(属性或initWithCustomView
)并UIImageView
用作该视图。那仍然不会为 gif 的“开箱即用”设置动画(刚刚检查过)。
如果你这样做,你有两个选择:
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 我发现这一行是不正确的:
[[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];
几点注意事项: