如何使用自定义UINavigationBar

时间:2012-04-04 06:33:29

标签: objective-c ios ios5

我有UINavigationBar的子类。

@interface MyNavigationBar : UINavigationBar

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

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

我希望_ navigationController 会有 MyNavigationBar

如何做到这一点?

感谢。

2 个答案:

答案 0 :(得分:4)

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

enter image description here

然后为了使实例化更容易,我将一个类别添加到`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];

答案 1 :(得分:1)

UINavigationController具有只读属性

@property(nonatomic, readonly) UINavigationBar *navigationBar

因为它是只读的,所以你必须继承UINavigationBar并重写此属性或使其成为read-write.E.g。 :

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

或继承:

MyNavigationController.h

@class MyNavigationBar;

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

MyNavigationController.m

@implementation MyNavigationController
@synthesize navigationBar = _navigationBar;
@end

然后改变

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

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