稍后在 View Controller 中更改 UINavigationBar

Changing UINavigationBar later in View Controller

我有一个没有 NavigationController(也不能)的视图控制器。我这样定义一个导航栏。

    UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 20, [UIScreen mainScreen].bounds.size.width, 41)];

    navBar.backgroundColor = UIColorFromRGB(0x72CE97);
    navBar.barTintColor = UIColorFromRGB(0x72CE97);

    //Keep the container for Navigation Items
    UINavigationItem *navItem = [[UINavigationItem alloc] init];
    UIImage* logoImage = [UIImage imageNamed:@"nav_logo_small.png"];
    navItem.titleView = [[UIImageView alloc] initWithImage:logoImage];

    //Add the left button as an Item to Navigation Items

    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:self action:@selector(backButton:)];
    navItem.leftBarButtonItem = leftButton;

    //Add Navigation Items Container to Navigation Bar
    navBar.items = @[ navItem ];

    //Display the Navigation Bar
    [self.view addSubview:navBar];
    [navBar release];

稍后如何在视图控制器中更改背景? 下面不行。我认为这是因为我没有 NavigationController:

NavigationBar *navigationBar = self.navigationController.navigationBar;
navigationBar.backgroundColor = [UIColor colorWithRed:197.0f/255.0f green:174.0f/255.0f blue:135.0f/255.0f alpha:1.0];
navigationBar.barTintColor = [UIColor colorWithRed:197.0f/255.0f green:174.0f/255.0f blue:135.0f/255.0f alpha:1.0];

试试这个:

UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 20, [UIScreen mainScreen].bounds.size.width, 41)];
navBar.tag = 1;
...
NavigationBar *navigationBar = (NavigationBar *)[self.view viewWithTag:1];