AJ112
AJ112

Reputation: 5301

Show / Hide UIBarButtonItem Depending On If The View Is Empty Or Not

I have a simple iPad project with a view having two containers. When the entries on the left side are selected, the right side gets updated with its details. The right view controller also has UIBarButtonItem on a toolbar that used UIActivityController to share its contents on different social networks. The button is connected with the IBAction as follow:

-(IBAction)Share:(id)sender
{    
    NSArray *activityItems = @[self.title, urlString];
    UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
    [self presentViewController:activityVC animated:YES completion:nil];

    [activityVC setCompletionHandler:^(NSString *activityType, BOOL completed)
     {
         NSLog(@"Activity = %@",activityType);
         NSLog(@"Completed Status = %d",completed);

         if (completed)
         {
             UIAlertView *objalert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Successfully Shared" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
             [objalert show];
             objalert = nil;
         } else
         {
             UIAlertView *objalert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Unable To Share" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
             [objalert show];
             objalert = nil;
         }
     }];
}

Everything works fine BUT when the app is opened for the very first time, the right side is empty and tapping on the Share button results in a crash.

How can i hide the bar button when the right view controller is empty and the bar button item appears only when there is content in the view controller ??

Thanks in advance.

Upvotes: 0

Views: 830

Answers (1)

rdelmar
rdelmar

Reputation: 104082

I don't know if there's a way to "hide" it, but you can set its enabled property to NO, when you first create the button in viewDidLoad. Or, you could just delay its creation until you update the right side with details.

How you then enable or create it, depends on what you're doing to update the right side. A common way would be to override the setter of something you're setting a value of when you do the update. For instance, if you were setting the value of a string property called detailString, you could do this:

-(void)setDetailString:(NSString *) newString {
    _detailString = newString;
    self.navigationItem.rightBarButtonItem.enabled = YES;
}

Upvotes: 1

Related Questions