在UINavigationBar(iOS)上将UIActivityIndi​​catorView添加到UIBarButtonItem

时间:2012-05-06 09:39:32

标签: ios iphone uibarbuttonitem uiactivityindicatorview

我找到了great article如何在导航栏上的Bar Button中添加活动指示器。但我不能在我的情况下重复这一点。我在代码中添加了导航栏和UIBarButton(不是在nib中),但我找不到一个名为UINavigationButton的元素来将Activity Indicator放入其中。

我希望UIBarButtonItem按钮可见:

enter image description here

而不是那样:

enter image description here

有没有人建议如何使这项工作?

2 个答案:

答案 0 :(得分:5)

粗略的解决方法可能是这样的:

 act=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
 [act setFrame:CGRectMake(14, 5, 20, 20)];
 [act startAnimating];
 rightButt=[[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleBordered target:self action:nil];
 self.navigationItem.rightBarButtonItem=rightButt;
 if ([[self.navigationController.navigationBar subviews] count]>=2) {
     //Be careful with the next line, Here you get access to an static index, 
     //Apple could change the structure of the navbar and your index may change in the future.
     [[[self.navigationController.navigationBar subviews] objectAtIndex:2] addSubview:act];    

    }

你会得到这个:

enter image description here

修改
从您的评论看来,您似乎想要在UIToolbar中添加此按钮,而不是在UINavigationBar中,它是完全相同的:

UIActivityIndicatorView* act=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
[act setFrame:CGRectMake(10, 13, 20, 20)];
[act startAnimating];
UIBarButtonItem *rightButt=[[UIBarButtonItem alloc] initWithTitle:@"      " style:UIBarButtonItemStyleBordered target:self action:nil];
UIToolbar *tb=[[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
[tb setBarStyle:UIBarStyleBlack];
[tb setItems:[NSArray arrayWithObjects:rightButt, nil]];
if ([[tb subviews] count]>=1) {
    [[[tb subviews] objectAtIndex:1] addSubview:act];      
}

你会得到这个:

enter image description here

答案 1 :(得分:0)

使用按钮并在其中添加活动指示器作为子视图