Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if a UIViewController has a back button

I have a category that extends the functionality of a UIViewController that adds its own subtitle to the title bar. It needs to know what buttons are present in the title bar so that it can resize the labels within. I can detect if there is a leftBarButtonItem and rightBarButtonItem, but when it comes to a backBarButtonItem everything I have tried tells me that there is no back button, when in fact there is one when the view loads. This is what I've used to test:

if(self.parentViewController.navigationItem.backBarButtonItem == nil){
    NSLog(@"no back button");
}
else {
    NSLog(@"has back button");
}

if(self.parentViewController.navigationController.navigationItem.backBarButtonItem == nil){
    NSLog(@"1no back button");
}
else {
    NSLog(@"1has back button");
}

if(self.navigationItem.backBarButtonItem == nil){
    NSLog(@"2no back button");
}
else {
    NSLog(@"2has back button");
}

if(self.navigationController.navigationItem.backBarButtonItem == nil){
    NSLog(@"3no back button");
}
else {
    NSLog(@"3has back button");
}

if(self.presentingViewController.navigationItem.backBarButtonItem == nil){
    NSLog(@"4no back button");
}
else {
    NSLog(@"4has back button");
}

if(self.presentingViewController.navigationController.navigationItem.backBarButtonItem == nil){
    NSLog(@"5no back button");
}
else {
    NSLog(@"5has back button");
}

if(self.presentedViewController.navigationItem.backBarButtonItem == nil){
    NSLog(@"6no back button");
}
else {
    NSLog(@"6has back button");
}

if(self.presentedViewController.navigationController.navigationItem.backBarButtonItem == nil){
    NSLog(@"7no back button");
}
else {
    NSLog(@"7has back button");
}

I've tried putting this in viewDidLoad, viewWillAppear and viewDidAppear, and they all return that there is no back button. In the previous view I do set the back button manually using self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:nil action:nil]; (The back button has to say back instead of the previous views title). Logically to me this means that the self.parentViewController is the one that should tell me if there is a back button on this view but clearly it doesn't.

like image 835
Fonix Avatar asked Nov 12 '22 15:11

Fonix


1 Answers

If current scenario is true and you are expecting back buttons to say "back" you can traverse subviews looking for that button.

BOOL exists = NO;
for (UIView *view in [self.view subviews]) {
    if ([view isMemberOfClass [UIButton class]]) {
        if([view.title isEqualToString: @"Back"]){
                exists = YES;
        }
    }
}
if(!exists){
     //Add back button
}

enter image description here

like image 106
propstm Avatar answered Nov 15 '22 06:11

propstm