简体   繁体   中英

Objective-C notation - UINavigationBar

I have the following method:

+(UINavigationBar*)insertTopbar
{
    UINavigationBar *navBar = [ [UINavigationBar alloc] initWithFrame:CGRectMake(0, 20, 320, 44)];
    NSString* navBarPortraitBackgroundPath = [[NSBundle mainBundle] pathForResource:@"navBarPortraitBackground" ofType:@"png"];

    navBar.topItem.title = @"MyApp";

    UINavigationItem *navAdd = [[UINavigationItem alloc] init];
    navAdd.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemAdd target:self action:@selector(addFood)];

    navAdd.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemDone target:self action:@selector(addFood)];


    [navBar pushNavigationItem:navAdd animated:YES];

    [[navBar appearance] setBackgroundImage: [UIImage imageWithContentsOfFile:navBarPortraitBackgroundPath] forBarPosition:UIBarPositionTopAttached barMetrics:UIBarMetricsDefault];

    return navBar;
}

And i implement it in some of my ViewControllers by writing [self.view addSubview:[KalorieTopbar insertTopbar]];

The problem is the line right before return navBar , when i try to set the appearence of the navBar. I think that there might be something wrong with my way of setting that, as i get the error: No visible @interface for 'UINavigationBar' declares the selector 'appearance'

Have a look into the documentation of UIAppearance: https://developer.apple.com/library/ios/documentation/uikit/reference/UIAppearance_Protocol/Reference/Reference.html#//apple_ref/occ/intfcm/UIAppearance/appearance

It is a class +method, not an instance -method. Therefore you need to call [UINavigationBar appearance] instead of [navBar appearance] .

The error is because a UINavigationBar instance does not have an appearance method.

The method setBackgroundImage:forBarPosition:barMetrics: is a method on a UINavigationBar instance as per Apple docs

So the line should be

[navBar setBackgroundImage: 
         [UIImage imageWithContentsOfFile:navBarPortraitBackgroundPath] 
      forBarPosition:UIBarPositionTopAttached 
      barMetrics:UIBarMetricsDefault];

This is new in IOS 7 and previously use the class method as per @cweinberger's answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM