我以编程方式生成了UIButtons,它们共享相同的选择器方法。当方法运行时,我希望方法知道按下了哪个按钮,然后能够加载相应的UIViewController。
-(void)buildButtons
{
for( int i = 0; i < 5; i++ ) {
UIButton* aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[aButton setTag:i];
[aButton addTarget:self action:@selector(buttonClicked:)forControlEvents:UIControlEventTouchUpInside];
[aView addSubview:aButton];
}
然后:
- (void)buttonClicked:(UIButton*)button
{
NSLog(@"Button %ld clicked.", (long int)[button tag]);
// code here that picks the correct viewController to push to...
// for example tag 1 would create an instance of vcTwo.m and would then be pushed to the navigationController and be displayed on screen
}
说我有三个UIViewController类(vcOne.m,vcTwo.m,vcThree.m),我希望它能够在按下按钮时运行'buttonClicked'并且代码选择相应的viewController来推送。我不想使用一系列if语句,因为最终可能有几十个/几百个viewControllers。我是否必须实例化所有viewControllers并将它们放在一个数组中?还有更好的方法吗?
答案 0 :(得分:1)
你在使用故事板吗?所以你可以根据按钮标签选择一个segue:
int i = (int)[button tag];
[self performSegueWithIdentifier:[NSString stringWithFormat:@"Segue%d", i] sender:self];
或:
UIViewController *viewController= [controller.storyboard instantiateViewControllerWithIdentifier:NSString stringWithFormat:@"ViewControllerNumber%d", i];
答案 1 :(得分:0)
最后我接受了这个:
- (void) buttonClicked:(id)sender
{
NSLog(@"Button tag = %li", (long)[sender tag]);
FormularyVC *formularyVCInstance = [FormularyVC alloc];
ProceduresVC *proceduresVCInstance = [ProceduresVC alloc];
VetMedVC *vetMedVCInstance = [VetMedVC alloc];
NSArray *vcArray = [NSArray arrayWithObjects:formularyVCInstance, proceduresVCInstance, vetMedVCInstance, nil];
UIViewController *vcToLoad = [vcArray objectAtIndex:(int)[sender tag]];
vcToLoad.view.backgroundColor = [UIColor whiteColor];
[self.navigationController pushViewController:vcToLoad animated:NO];
}
我根据按下的按钮创建了一个我希望能够加载的ViewControllers数组。按下按钮时,将运行方法并将标记作为参数。此标记用于通过检查其在数组索引上的位置来查找所需的ViewController。