我有幾個視圖控制器和表視圖控制器,我從根視圖控制器推。在所有這些中,我想在導航控制器中使用自定義後退按鈕。而不是複製方法來設置我的後退按鈕到每個類,文件中,我創建了一個輔助類和一個類方法來完成設置。下面的代碼工作,但我想知道如果我以錯誤的方式去做。有沒有更好的方法來實現這一目標?另外,我仍然在所有類中複製 - (void)myCustomBack方法,並且想知道是否有辦法避免這種情況。目標C中跨類共享方法的最佳方式是什麼?
@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
不錯的選擇。這種模式非常好,我從不後悔使用它。由於我注意到這是你的第一個問題,你應該點擊複選標記來接受答案。無論是Josh Caswell還是你自己的答案,在我看來都是很好的選擇,但這顯然是你自己的決定。好的第一個問題,希望看到你繼續貢獻,祝你好運。 –
@CarlVeazey - 謝謝!由於這是我的第一個問題,我仍然有點不確定標記答案的禮節。當我去研究如何創建一個類別時,我確實閱讀了所有答案,並考慮了所有答案。另外,我想等待迴應,並且可以更好地解決問題。但在這一點上,我認爲我的工作很好。 – Dylan