0

我有UINavigationBar.

@interface MyNavigationBar : UINavigationBar

进行了一些更改,现在希望我的应用程序NavigationController可以使用它:

 _navigationController = [[UINavigationController alloc] initWithRootViewController:self.viewController];
 [_window addSubview:[_navigationController view]];
[self.window makeKeyAndVisible];

我希望 _ navigationControllerMyNavigationBar

怎么可能做到这一点?

谢谢。

4

2 回答 2

4

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

在此处输入图像描述

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

@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

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

#import "UINavigationController+DSCNavigationController"

然后使用它看起来像

MyViewController *myViewController = [[MyViewController  alloc] init];
UINavigationController *navigationController = [UINavigationController dsc_navigationControllerWithRootViewController:myViewController];
于 2012-04-04T08:54:52.117 回答
1

UINavigationController 具有只读属性

@property(nonatomic, readonly) UINavigationBar *navigationBar

因为它是只读的,所以您必须继承 UINavigationBar 并覆盖此属性或使其为 read-write.Eg :

MyNaviagtionBar *myBar = [[MyNavigationBar alloc] init];
_navigationController.navigationBar = mybar;

或子类化:

我的导航控制器.h

@class MyNavigationBar;

@interface MyNavigationController : UINavigationController
@property(nonatomic, strong) MyNavigationBar *navigationBar;
@end

我的导航控制器.m

@implementation MyNavigationController
@synthesize navigationBar = _navigationBar;
@end

然后改变

_navigationController = [[UINavigationController alloc] initWithRootViewController:self.viewController];

_navigationController = [[MyNavigationController alloc] initWithRootViewController:self.viewController];
于 2012-04-04T07:59:27.570 回答