Skip to content

Instantly share code, notes, and snippets.

@nandodelauni
Last active December 18, 2015 12:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nandodelauni/5780400 to your computer and use it in GitHub Desktop.
Save nandodelauni/5780400 to your computer and use it in GitHub Desktop.
UIViewController category for creating a custom back button
- (UIBarButtonItem *)customBackButton
{
return [self customBackButtonWithTitle:nil];
}
- (UIBarButtonItem *)customBackButtonWithTitle:(NSString *)title
{
// if we have no title, search at the current navigation controller stack for the previous title
if (!title) {
id aViewController = nil;
for (int i = 0; i < self.navigationController.viewControllers.count; i++) {
aViewController = self.navigationController.viewControllers[i];
if ([self isMemberOfClass:[aViewController class]]) {
// no checking if you are calling this from rootViewController :)
id previousViewController = self.navigationController.viewControllers[i-1];
title = [previousViewController valueForKey:@"title"];
break;
}
}
}
self.navigationItem.hidesBackButton = YES;
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
[backButton setFrame:CGRectMake(0, 0, 47, 29)];
[backButton setBackgroundImage:[UIImage imageNamed:@"backBTN_bg.png"] forState:UIControlStateNormal];
[backButton setTitle:title forState:UIControlStateNormal];
[backButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 0)];
backButton.titleLabel.font = [UIFont boldSystemFontOfSize:10];
[backButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[backButton addTarget:self action:@selector(backButtonTapped) forControlEvents:UIControlEventTouchUpInside];
return [[UIBarButtonItem alloc] initWithCustomView:backButton];
}
- (void)backButtonTapped
{
[self.navigationController popViewControllerAnimated:YES];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment