且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用自定义 UINavigationBar

更新时间:2023-02-25 21:41:48

你必须创建一个带有 UINavaigationController 的 xib.然后,您可以在 Interface Builder 中选择 navigationBar 并将类更改为 UINavigationBar 的子类.

You have to create a xib with a UINavaigationController in it. You can then select the navigationBar in Interface Builder and change the class to your subclass of UINavigationBar.

然后为了更容易实例化,我向 `UINavigationController 添加了一个类别,例如:

Then to make this a little easier to instantiate I add a category to `UINavigationController like:

@interface UINavigationController (DSCNavigationController)

+ (UINavigationController *)dsc_navigationControllerWithRootViewController:(UIViewController *)rootViewController;

@end

@implementation UINavigationController (DSCNavigationController)

+ (UINavigationController *)dsc_navigationControllerWithRootViewController:(UIViewController *)rootViewController;
{
    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"DSCNavigationController" owner:nil options:nil];

    NSAssert(1 == [topLevelObjects count], @"DSCNavigationController should have one top level object");

    UINavigationController *navigationController = [topLevelObjects objectAtIndex:0];

    NSAssert([navigationController isKindOfClass:[UINavigationController class]], @"Should have a UINavigationController");

    [navigationController pushViewController:rootViewController animated:NO];

    return navigationController;
}

@end

在使用它的类的顶部,确保在我的情况下导入类别,它看起来像

At the top of the class that uses it makes sure to import the category in my case it looks like

#import "UINavigationController+DSCNavigationController"

然后使用它看起来像

MyViewController *myViewController = [[MyViewController  alloc] init];
UINavigationController *navigationController = [UINavigationController dsc_navigationControllerWithRootViewController:myViewController];