我在这里和其他网站上看到的所有示例都涉及创建UIActivityIndicatorView并使用以下内容加载它:
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:myActivityIndicatorView target:nil action:nil] autorelease];
但是,这只是在导航栏中创建一个普通活动指示器.我想要做的是有一个看起来像普通的UIBarButtonSystemItem按钮,但有一个活动指示器,而不是一个默认图像.我尝试使用nil图像或标题执行initWithImage和initWithTitle,然后将活动指示符添加为子视图,但这不起作用.
有任何想法吗?
我的解决方案是创建UIButton的子类:
在SOActivityButton.h中:
@interface SOActivityButton : UIButton { UIActivityIndicatorView* activityIndicator; } @end
在SOActivityButton.m中:
@implementation SOActivityButton - (id)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { CGRect innerFrame = CGRectInset(frame, 8.0f, 8.0f); activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:innerFrame]; activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite; [self addSubview:activityIndicator]; } return self; } - (void)dealloc { [activityIndicator release], activityIndicator = nil; [super dealloc]; } - (void) startAnimating { [activityIndicator startAnimating]; } - (void) stopAnimating { [activityIndicator stopAnimating]; } @end
然后使用它:
SOActivityButton* activityButton = [[SOActivityButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)]; [activityButton setImage:[UIImage imageNamed:@"button-background.png"] forState:UIControlStateNormal]; [activityButton addTarget:self action:@selector(myAction:) forControlEvents:UIControlEventTouchUpInside]; UIBarButtonItem *activityBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:activityButton]; [activityButton release]; self.navigationItem.rightBarButtonItem = activityBarButtonItem; [activityBarButtonItem release];
您需要找到或创建一个button-background.png.这里的PSD 应该有一个.