Unable to add UIScrollView to UINavigationBar

521 views Asked by At

I want my scrollview to be added as UINavigationBar's titleview, but strangely I am unable to do so.

In viewDidLoad:

navController = [[UINavigationController alloc] init];
    self.view.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 20 - 45 - 2);
    CGRect frame = navController.view.frame;
    frame.size.height -= 20;
    [self.view addSubview:navController.view];

    UIScrollView *someview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
    someview.backgroundColor = [UIColor orangeColor];
    navController.navigationItem.titleView = someview;

It is a very simple piece of code, but I can't figure out that what I am missing. Please someone help me... Thanks.

Side Note: I am initiating UINavigationController without any root controller, since my first concern is adding scrollview to navigationbar.

2

There are 2 answers

5
Wain On BEST ANSWER

navController.navigationItem is never actually added to the navigation bar. It exists because the nav controller is a subclass of UIViewController. But it isn't used.

Add a root view controller to the nav controller and add the scroll view as its navigationItem titleView.

Depending on what you're after you may also want to subclass the nav controller to inject your custom titleView when any new view controller is pushed.

0
pablomatico On

Have you tried to add the scroll view to a container view. Something like this:

navController = [[UINavigationController alloc] init];
self.view.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 20 - 45 - 2);
CGRect frame = navController.view.frame;
frame.size.height -= 20;
[self.view addSubview:navController.view];

UIView *container = [[UIView alloc] initWithFrame:CGRectMake(...)];
UIScrollView *someview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
someview.backgroundColor = [UIColor orangeColor];
[container addSubview:someview];
navController.navigationItem.titleView = container;