我有几个从根视图控制器推送的视图控制器和表视图控制器。在所有这些中,我想在导航控制器中使用自定义后退按钮。我没有将设置后退按钮的方法复制到每个类文件中,而是创建了一个辅助类,其中包含一个执行设置的类方法。下面的代码有效,但我想知道我是否以错误的方式处理这个问题。有没有更好的方法来实现这一目标?另外,我仍然在我的所有课程中复制 -(void)myCustomBack 方法,并且想知道是否也有办法避免这种情况。
@interface NavBarBackButtonSetterUpper : NSObject
+ (UIButton *)navbarSetup:(UIViewController *)callingViewController;
@end
@implementation NavBarBackButtonSetterUpper
+ (UIButton *)navbarSetup:(UIViewController *)callingViewController
{
callingViewController.navigationItem.hidesBackButton = YES;
UIImage *backButtonImage = [[UIImage imageNamed:@"back_button_textured_30"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 13, 0, 5)];
UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
[backButton setBackgroundImage:backButtonImage forState:UIControlStateNormal];
[backButton setTitle:@"Back" forState:UIControlStateNormal];
backButton.titleLabel.font = [UIFont fontWithName:@"AmericanTypewriter-Bold" size:12];
backButton.titleLabel.shadowOffset = CGSizeMake(0,-1);
UIView *customBackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
[customBackView addSubview:backButton];
callingViewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:customBackView];
return backButton;
}
@end
@interface MyCustomTableViewController : UITableViewController
@end
@implementation MyCustomTableViewController
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *backButton = [NavBarBackButtonSetterUpper navbarSetup:self];
[backButton addTarget:self action:@selector(myCustomBack) forControlEvents:UIControlEventTouchUpInside];
}
- (void)myCustomBack
{
[self.navigationController popViewControllerAnimated:YES];
}
@end
@interface MyCustomViewController : UIViewController
@end
@implementation MyCustomViewController
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *backButton = [NavBarBackButtonSetterUpper navbarSetup:self];
[backButton addTarget:self action:@selector(myCustomBack) forControlEvents:UIControlEventTouchUpInside];
}
- (void)myCustomBack
{
[self.navigationController popViewControllerAnimated:YES];
}
@end