Set a custom subclass of UINavigationBar in UINavigationController programmatically

前端 未结 12 1535
清歌不尽
清歌不尽 2020-11-28 17:29

Does anyone know how can I use my custom subclass of UINavigationBar if I instantiate UINavigationController programmatically (without IB)?

<
12条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 18:08

    Update: Using object_SetClass() no longer works as if iOS5 GM. An alternate solution has been added below.

    Use NSKeyedUnarchiver to manually set the unarchive class for the nav bar.

       MyViewController *controller = [[[MyViewController alloc] init] autorelease];
       NSKeyedUnarchiver *unarchiver = [[[NSKeyedUnarchiver alloc] initForReadingWithData:[NSKeyedArchiver archivedDataWithRootObject:controller]] autorelease];
       [unarchiver setClass:[MyNavigationBar class] forClassName:@"UINavigationBar"];
       controller = [unarchiver decodeObjectForKey:@"root"];
    




    Note: This original solution only works pre-iOS5:

    There is a great solution, which I posted here -- inject navBar subclass directly into your view the UINavigationController:

    #import 
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    
        object_setClass(self.navigationController.navigationBar, [MyNavBar class]);
        // the rest of your viewDidLoad code
    }
    

提交回复
热议问题