Showing a UIProgressView inside or on top of a UINavigationController's UINavigationBar

h345k34cr picture h345k34cr · Oct 6, 2013 · Viewed 15.6k times · Source

I want to have an UIProgressView to show a progress on the bottom of a navigation bar (just like when sending an iMessage or text message in iOS 7). But I need this consistently on every table view view of my navigation controller. So for me it was clear: I have to add this to the UINavigationController. But the problem is, it's not possible to add an UIProgressView to the UINavigationController. So I tried out two things:

1st I tried to add it to UINavigationController's view programmatically. But the problem was to position the UIProgressView and to make it look good when changing device rotation.

The 2nd thing I tried is to add the UIProgressView to every UITableView, but then I really have to do this for every view. Also it doesn't look good, because it is not on top of the navigation bar but beneath it. But the main reason why I didn't like the 2nd solution is because the ProgressViews go and come with their TableView, so you don't have a static one but changing ones.

After this, I don't have any idea to do this, so I ask you… does anyone have an idea how to do this?

That's how it should look like: enter image description here

Answer

h345k34cr picture h345k34cr · Oct 7, 2013

I finally found a solution:

I made a custom UINavigationController and added this to viewDidLoad

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    progress = [[UIProgressView alloc] init];

    [[self view] addSubview:progress];

    UIView *navBar = [self navigationBar];


    [[self view] addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[navBar]-[progress(2@20)]"
                                                                        options:NSLayoutFormatDirectionLeadingToTrailing
                                                                        metrics:nil
                                                                          views:NSDictionaryOfVariableBindings(progress, navBar)]];

    [[self view] addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[progress]|"
                                                                        options:NSLayoutFormatDirectionLeadingToTrailing
                                                                        metrics:nil
                                                                          views:NSDictionaryOfVariableBindings(progress)]];

    [progress setTranslatesAutoresizingMaskIntoConstraints:NO];

    [progress setProgress:0 animated:NO];
}

I created a new UIProgressView (I declared in @interface) added the constraints to position it beneath the navigation bar and (this step is important:) set translatesAutoresizingMaskIntoConstraints to NO.