将UIActivityIndicatorView添加到UINavigationBar上的UIBarButtonItem(iOS)

5
我找到了一篇关于如何在导航栏上的“Bar Button”中添加活动指示器的好文章。但是,在我的情况下,我无法重复此操作。我已经在代码中添加了导航栏和“UIBarButton”,但我找不到一个名为“UINavigationButton”的元素来放置活动指示器。
我希望UIBarButtonItem按钮是可见的: enter image description here 而不是这样: enter image description here 是否有人有建议如何使其正常工作?
2个回答

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];    

    }

您将会得到如下内容:

在此输入图片描述

编辑:
从您的评论中看来,您想要将此按钮添加到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];      
}

并且你将会得到这个:

在此输入图片描述


我有一个按钮,它与其他按钮在一起,所以我需要采取不同的步骤。但很可能就是这样。我会尝试并让你知道。 - Borut Tomazin
不,它在一个UINavigationBar内部。这在我的机器上可以工作,问题出在哪里? - Mat
没错,你已经将它放在了UINavigationBar中,但我将其放在了UIToolbar(三个barButtonItems)中,而UIToolbar也被放置在UINavigationBar的左/右侧。区别在于我将按钮包装到了UIToolbar中,而不是直接放在navigationBar上... 有什么建议吗? - Borut Tomazin
因为我的工具栏里有多个按钮,正如你所知道的,左/右barButtonItem只能容纳一个。 - Borut Tomazin
不,这也适用于iOS 5,在其中没有新的/弃用的功能。 - Mat
显示剩余2条评论

0
使用一个按钮,并将活动指示器作为其子视图添加进去。

这不是我想要的。我在我的问题中添加了额外的解释。看一下... - Borut Tomazin
第二种方法是添加两个指示器,一个放在按钮后面的栏上,另一个作为子视图放在按钮内部,这次不要减少按钮的透明度,当您禁用它时,后置指示器将自动可见。 - Saad
我在导航栏中显示指示器没有问题,但是将其显示在带有可见按钮的条形按钮项中时存在问题。问题在于,无论何时使用initWithCustomView,按钮本身都会被隐藏。不幸的是,您提供的建议都不起作用。 - Borut Tomazin
像这样的代码:UIButton* btn= [UIButton alloc] init]; [btn addSubview:activityIndicator]; self.navigationbarButton = btn;请完成其他部分的代码。 - Saad
1
是的,那就是我做的。但我无法将btn分配给navigationBarButton - 不兼容的指针类型,从'UIButton *__strong'分配到'UIBarButtonItem *'。 - Borut Tomazin
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接