0

我正在尝试使用利用 UINavigationBar 的自定义子类的 UINavigationController。但是,我遇到了 initWithFrame 的问题。当调用 initWithFrame 时,我打印出尺寸,它显示 0.0 宽度和 0.0 高度。但是,当我在 UINavigationBar 子类的 -(void) layoutSubviews 中打印出相同的框架时,该框架已正确设置。为什么 initWithFrame 接收到零大小的帧,我能做些什么来解决这个问题?手动调用 initWithFrame 或类似的东西听起来不正确,因为 UINavigationController 应该处理这个问题。以下是相关代码:

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    UINavigationController *navController = [[UINavigationController alloc] initWithNavigationBarClass:[CustomNavigationBar class] toolbarClass:nil];
    CoolViewController *vc = [[CoolViewController alloc] init];
    [navController pushViewController:vc animated:YES];
    self.window.rootViewController = navController;

    [self.window makeKeyAndVisible];

    return YES;
}

自定义导航栏.m

- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        NSLog(@"initWithFrame with frame: %f, %f", frame.size.width, frame.size.height); // This prints "initWithFrame with frame: 0, 0"
    }

    return self;
}

谢谢!

4

1 回答 1

1

I believe the navigation controller doesn't actually set the frame size to a specified value. Instead, it asks the navigation bar for its sizeThatFits: and uses that. By definition, that can't be done and passed to initWithFrame:. So, you want to use a combination of sizeThatFits:, setFrame: and layoutSubviews to add, size and reset your navigation bar content.

于 2013-06-15T07:22:58.400 回答