【发布时间】:2019-05-07 23:25:54
【问题描述】:
我以编程方式生成了所有共享相同选择器方法的 UIButton。当方法运行时,我希望该方法知道按下了哪个按钮,然后能够加载相应的 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 语句,因为最终可能有几十个/几百个 viewController。我是否必须实例化所有的 viewController 并将它们放在一个数组中?有没有更好的办法?
【问题讨论】:
-
每个按钮都有一个
tag属性。您可以使用它来区分按下了哪个按钮。 :) -
@karthikeyan - 这些一定是更好的方法吗?还是我错过了什么?如果有 100 个 viewController 会怎样?我需要一个 100 个 case 长的 switch 语句,然后是 100 个硬编码方法。看起来不是很OO。
-
@AbhishekBedi - 你会在我的问题中看到我已经在捕获按钮的标签属性的值并从那里开始工作;)
-
你必须实例化所有的 viewController 并将它们放在数组中 - (void)buttonClicked:(UIButton*)button { NSLog(@"Button %ld clicked.", (long int)[button tag ]); NSInteger 标签=[按钮标签]; [self.navigationController pushViewController:[commonArray objectAtIndex:tag] 动画:YES]; }
标签: ios iphone objective-c cocoa-touch