在导航栏上方添加视图

obe*_*tie 2 iphone objective-c uinavigationbar ios ios7

我正在尝试实现类似于在iOS 7上的新消息应用程序(Safari也是如此)中看到的效果,其中导航栏本身内有一个进度条:

进度条在iOS 7的导航栏中看到

我尝试了几种方法,并找到一种几乎可行的方法.我正在使用的是一个自定义子类,UINavigationBar它在初始化时将我的自定义进度条添加为子视图.这工作得很好,但是当我尝试添加NSLayoutConstraints它时应用程序崩溃了.

工作代码(没有布局约束,因此不适应方向更改):

- (void)commonInit
{
    if (!self.progressIndicator) {
        self.progressIndicator = [[ECourseProgressIndicatorView alloc] initWithFrame:CGRectMake(0, self.bounds.size.height - 3, self.bounds.size.width, 3)];
        [self addSubview:self.progressIndicator];
    }
}
Run Code Online (Sandbox Code Playgroud)

代码我希望能够使用(NSLayoutConstraint添加s),但崩溃:

- (void)commonInit
{
    if (!self.progressIndicator) {
        self.progressIndicator = [[ECourseProgressIndicatorView alloc] initWithFrame:CGRectMake(0, self.bounds.size.height - 3, self.bounds.size.width, 3)];
        [self addSubview:self.progressIndicator];

        self.progressIndicator.translatesAutoresizingMaskIntoConstraints = NO;
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-0-[progressIndicator]-0-|" options:0 metrics:nil views:@{@"progressIndicator": self.progressIndicator}]];
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[progressIndicator(==3)]-0-|" options:0 metrics:nil views:@{@"progressIndicator": self.progressIndicator}]];
    }
}
Run Code Online (Sandbox Code Playgroud)

运行具有布局约束的代码时遇到的错误包含在此处的Gist中.如果我没有设置translatesAutoresizingMaskIntoConstraints = NO,那么代码可以工作,但我指定的布局约束将被忽略,以支持自动调整大小的掩码约束.

谁能摆脱任何光明?

PS我最初想到将进度条添加为UINavigationBar上方的视图(所以根本不在其层次结构中),但是我找不到有关如何在导航栏上方直观地定位视图的信息(以Z坐标术语表示) ,而不是Y).

注意:我在Apple开发人员论坛中发布了这个,但没有得到回复.

Jos*_*son 5

诀窍是将视图添加到navigationItem的titleView.将该视图的cliptobounds设置为NO,并在其中添加进度视图.

UIView *test = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 128, 33)];
[test setBackgroundColor:[UIColor redColor]];
[test setClipsToBounds:NO];


// Add the progress view
UIProgressView *progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];
[progressView setFrame:CGRectMake(-96, 36, 320, 2)];
[progressView setProgress:1.0];
[progressView setProgressTintColor:SYSTEM_BLUE];


[test addSubview:progressView];

self.navigationItem.titleView=test;
Run Code Online (Sandbox Code Playgroud)