0

有没有办法将像 Apple 旋转齿轮这样的动画图像设置为 UIBarButtonItem?

我试过这行代码,但动画 gif 图像无法播放:

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

4 回答 4

2

尝试创建 aUIActivityIndicatorView并将其分配给您的按钮-[UIBarButtonItem initWithCustomView:]

于 2010-01-18T22:33:26.257 回答
0

我认为 UIBarButtonItem 不可能。

您可能希望customView用于该(属性或initWithCustomView)并UIImageView用作该视图。那仍然不会为 gif 的“开箱即用”设置动画(刚刚检查过)。

如果你这样做,你有两个选择:

  • 从 UIImageView 类使用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];

于 2010-01-18T22:53:37.520 回答
0

我发现这一行是不正确的:

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

... Apple 默认刷新按钮的实际大小略有不同。如果您有其他项目在该工具栏上进行自动布局,则需要正确调整大小。

不幸的是,Apple 没有提供用于查找大小的API 。通过反复试验,这似乎是正确的:

[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 28, 28)];
于 2010-07-29T12:36:21.763 回答
0

为此,我将 UIBarButtonItem 的 customView 设置为带有图标图像的 UIButton,然后添加 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 的背景图像。
于 2013-02-24T21:41:47.473 回答