ios – 在Objective C中在课堂上分享方法的最佳方式是什么?

我有几个视图控制器和表视图控制器,从我的根视图控制器.在所有这些中,我想在导航控制器中使用自定义后退按钮.而不是复制方法来设置我的后退按钮到每个类,文件,我已经创建了一个帮助类与类方法进行安装.下面的代码可以正常工作,但是我想知道我是否会错过这个方法.有没有更好的方式来实现这一点?此外,我仍然在我的所有类中复制 – (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,5)];

    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(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,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的子类,并让您的所有自定义视图控制器都继承自此自定义子类. “父”子类将具有 – (void)myCustomBack以及设置代码,您将不再需要重复.

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...