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

前端之家收集整理的这篇文章主要介绍了ios – 在Objective C中在课堂上分享方法的最佳方式是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有几个视图控制器和表视图控制器,从我的根视图控制器.在所有这些中,我想在导航控制器中使用自定义后退按钮.而不是复制方法来设置我的后退按钮到每个类,文件,我已经创建了一个帮助类与类方法进行安装.下面的代码可以正常工作,但是我想知道我是否会错过这个方法.有没有更好的方式来实现这一点?此外,我仍然在我的所有类中复制 – (void)myCustomBack方法,并且想知道是否有办法避免这种情况.
  1. @interface NavBarBackButtonSetterUpper : NSObject
  2. + (UIButton *)navbarSetup:(UIViewController *)callingViewController;
  3. @end
  4.  
  5. @implementation NavBarBackButtonSetterUpper
  6.  
  7. + (UIButton *)navbarSetup:(UIViewController *)callingViewController
  8. {
  9. callingViewController.navigationItem.hidesBackButton = YES;
  10.  
  11. UIImage *backButtonImage = [[UIImage imageNamed:@"back_button_textured_30"] resizableImageWithCapInsets:UIEdgeInsetsMake(0,13,5)];
  12.  
  13. UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0,50,30)];
  14.  
  15. [backButton setBackgroundImage:backButtonImage forState:UIControlStateNormal];
  16.  
  17. [backButton setTitle:@"Back" forState:UIControlStateNormal];
  18. backButton.titleLabel.font = [UIFont fontWithName:@"AmericanTypewriter-Bold" size:12];
  19. backButton.titleLabel.shadowOffset = CGSizeMake(0,-1);
  20.  
  21. UIView *customBackView = [[UIView alloc] initWithFrame:CGRectMake(0,30)];
  22. [customBackView addSubview:backButton];
  23.  
  24. callingViewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:customBackView];
  25.  
  26. return backButton;
  27. }
  28. @end
  29.  
  30.  
  31.  
  32. @interface MyCustomTableViewController : UITableViewController
  33. @end
  34.  
  35. @implementation MyCustomTableViewController
  36.  
  37. - (void)viewDidLoad
  38. {
  39. [super viewDidLoad];
  40.  
  41. UIButton *backButton = [NavBarBackButtonSetterUpper navbarSetup:self];
  42.  
  43. [backButton addTarget:self action:@selector(myCustomBack) forControlEvents:UIControlEventTouchUpInside];
  44. }
  45.  
  46. - (void)myCustomBack
  47. {
  48. [self.navigationController popViewControllerAnimated:YES];
  49. }
  50. @end
  51.  
  52.  
  53. @interface MyCustomViewController : UIViewController
  54. @end
  55.  
  56. @implementation MyCustomViewController
  57.  
  58. - (void)viewDidLoad
  59. {
  60. [super viewDidLoad];
  61.  
  62. UIButton *backButton = [NavBarBackButtonSetterUpper navbarSetup:self];
  63.  
  64. [backButton addTarget:self action:@selector(myCustomBack) forControlEvents:UIControlEventTouchUpInside];
  65. }
  66.  
  67. - (void)myCustomBack
  68. {
  69. [self.navigationController popViewControllerAnimated:YES];
  70. }
  71. @end

解决方法

我认为你的问题的解决将是继承.

您可以创建一个UIViewController的子类,并让您的所有自定义视图控制器都继承自此自定义子类. “父”子类将具有 – (void)myCustomBack以及设置代码,您将不再需要重复.

猜你在找的iOS相关文章