3

我想添加一个加载活动指示器到我的应用程序,类似于邮件应用程序中的状态文本在右边。我使用的是UINavigationController,所以我知道我需要在每个视图上设置toolbarItems数组,使其显示在我想要的位置。我可以添加活动指示器并显示,但是当我尝试使用下面的代码添加文本字段时,文本不显示。有没有一种方法可以通过编程方式创建一个容器,其中包含状态文本和UIActivityIndi​​catorView,如果将其添加到toolbarItems数组中,它们将显示出来。UINavigationController工具栏 - 使用UIActivityIndi​​catorView添加状态文本

UIBarButtonItem *textFieldItem = [[[UIBarButtonItem alloc] initWithCustomView:textField] autorelease]; 
self.toolbarItems = [NSArray arrayWithObject:textFieldItem]; 

UPDATE: 我创建从UIView的派生的类基于从pdriegen的代码。
我还添加了此代码viewDidLoad中在我的控制器

UIProgressViewWithLabel * pv = [[UIProgressViewWithLabel alloc] init]; 

UIBarButtonItem * pvItem = [[UIBarButtonItem alloc] initWithCustomView:pv]; 

[self setToolbarItems:[NSMutableArray arrayWithObject:pvItem]]; 

目前没有在工具栏上显示出来。我错过了什么?

+0

您是否尝试过使用一个UILabel? –

+0

它可能是一个间距问题...添加一个灵活的空间项目 – jmstone617

+0

感谢您的建议。仍然只显示活动指标。你看到我的例子有什么问题吗? – Lee

回答

10

不是将活动指示器和标签添加为单独的视图,而是创建一个包含它们的复合视图并将该复合视图添加到工具栏。

创建一个从UIView的派生的类,覆盖initWithFrame并添加以下代码:

- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
     // Initialization code 
     [self configureView]; 
    } 
    return self; 
} 

-(void)configureView{ 

    self.backgroundColor = [UIColor clearColor]; 

    UIActivityIndicatorView* activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];   
    activityIndicator.frame = CGRectMake(0, 0, self.frame.size.height, self.frame.size.height); 
    activityIndicator.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth; 
    activityIndicator.backgroundColor = [UIColor clearColor]; 

    [self addSubview:activityIndicator]; 

    CGFloat labelX = activityIndicator.bounds.size.width + 2; 

    UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(labelX, 0.0f, self.bounds.size.width - (labelX + 2), self.frame.size.height)]; 
    label.autoresizingMask = UIViewAutoresizingFlexibleWidth; 
    label.font = [UIFont boldSystemFontOfSize:12.0f]; 
    label.numberOfLines = 1; 

    label.backgroundColor = [UIColor clearColor]; 
    label.textColor = [UIColor whiteColor]; 
    label.text = @"Loading.."; 

    [self addSubview:label]; 
} 

你也不得不暴露了startAnimating,stopAnimating和一个方法来设置标签的文本,但希望你明白了。

将其添加到您的工具栏,初始化如下:

UIProgressViewWithLabel * pv = [[UIProgressViewWithLabel alloc] initWithFrame:CGRectMake(0,0,150,25)]; 

玩的宽度,使之适合..

+0

谢谢,这看起来正是我所需要的,但我仍然无法让它显示出来。我根据您的回复更新了我的问题。 – Lee

+0

如果我在进度视图上开始动画,它会显示,但仍然没有标签。 – Lee

+0

@Lee我已经编辑了我的答案,在最后添加了一个额外的代码行,可以帮助您。 – pdriegen

相关问题