我注意到我有一组用于产品过滤系统的 UIViewController,它们使用完全相同的代码。此代码基本上为 UIToolBar
创建按钮,并隐藏呈现它的 Controller 的 UIToolBar
。唯一的区别是标题上写着“精炼:”。
在每个页面上,我都会在“优化依据”之后显示页面类型,例如:在性别过滤页面上,它会显示“优化依据:然后我将附加另一个粗体字符串,上面写着”性别对于产品类型页面,我将附加一个粗体字符串,表示“产品类型”等。
以下是在连接到这些 Controller 的每个自定义类中重复的代码:
@property (weak, nonatomic) IBOutlet UIToolbar *toolBar;
@end
@implementation VAGRefineProductTypeViewController
{
VAGRefineProductTypeViewController *_thisController;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
// Custom initialization
_thisController = self;
}
return self;
}
- (void)viewDidLoad
{
UIToolbar *toolBar = [_thisController toolBar];
[[_thisController navigationItem] setLeftBarButtonItem:nil];
[_thisController setTitle:@"R E F I N E B Y:"];
// Setup buttons for tool bar
UIButton *clearButton = [[UIButton alloc] initWithFrame:CGRectMake(40, 3, 110, 38)];
UIButton *doneButton = [[UIButton alloc] initWithFrame:CGRectMake(170, 3, 110, 38)];
[clearButton setBackgroundColor:[UIColor darkGrayColor]];
[doneButton setBackgroundColor:[UIColor blackColor]];
[clearButton setTitle:@"Clear" forState:UIControlStateNormal];
[doneButton setTitle:@"Done" forState:UIControlStateNormal];
[clearButton addTarget:_thisController action:@selector(clearButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
[doneButton addTarget:_thisController action:@selector(doneButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
// Add buttons to toolbar
[toolBar addSubview:clearButton];
[toolBar addSubview:doneButton];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// Hide previous pages tool bar
[[_thisController navigationController] setToolbarHidden:YES animated:NO];
}
- (IBAction)clearButtonTapped:(id)sender {
NSLog(@"CLEAR BUTTON TAPPED");
}
- (IBAction)doneButtonTapped:(id)sender {
NSLog(@"DONE BUTTON TAPPED");
}
这个UIToolBar
被添加到界面构建器中的每个UIViewController
中。隐藏在 viewWillAppear 中的那个是从 UIViewController
以编程方式添加的那个,它呈现当前的 UIViewController
。
问题:
与其将此代码复制并粘贴到每个 UIViewController
的类文件中,不如将其放入一个文件中并在每个 UIViewController
中使用该文件?
最佳答案
您有多种选择。可能最简单的方法是定义一个基类 UIViewController 来定义共享属性和方法,然后使所有使用这些属性的 View Controller 成为该类的子类。
另一种选择是定义一个定义新方法的 UIViewController 类别。但是,这不允许您向 View Controller 添加新的属性或实例变量(至少不是没有技巧。)
关于ios - 如何在文件之间重用相同的代码并可以选择在 Objective-C 中传递参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23439031/