我有几个视图控制器和表格视图控制器,它们都是从我的根视图控制器推出的。我想在所有这些控制器中使用自定义返回按钮来替代默认的返回按钮。为了避免将设置自定义返回按钮的方法复制到每个类或文件中,我创建了一个助手类,并编写了一个类方法来处理此操作。下面的代码可以工作,但是我想知道是否有更好的方法来实现这一点。而且,我仍然需要在所有的类中重复方法 -(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
UIViewController
和UITableViewController
创建子类吗?那么我还是要在两个地方重复代码。 - Dylan