【问题标题】:In UIViewController how can I have a single method automatically handle a lot of buttons在 UIViewController 我怎样才能有一个方法自动处理很多按钮
【发布时间】:2011-10-12 03:21:29
【问题描述】:

我有一个UIViewController 用于 iPad 应用程序,用户可以通过触摸 80 个按钮之一来选择 80 个谜题之一。除了手动将 80 UIButton 连接到 IBAction 方法之外,有没有办法以编程方式或其他一些巧妙的方式做到这一点?

当然,另一种选择是构建自定义视图并自己完成所有工作,但我想知道上述是否可以变得更容易。

【问题讨论】:

  • Google:" uitableview SQLite" 我会给你更多关于 SQLite 的信息,但我自己是个菜鸟。它会让你的生活轻松一百万倍。

标签: ios ipad uiviewcontroller


【解决方案1】:

您的意思是 80 个 UIButtons 对应 80 个动作还是 80 个按钮对应 1 个动作? 您可以使用以下方式以编程方式添加所有按钮: .h

 @interface myfile : UIViewController {
IBOutlet UIButton *button;
}

.m

- (void)viewDidLoad{

[button setTitle:@"1" forState: UIControlStateNormal];
button.frame = CGRectMake (x position, y position, width, height);
 [button addTarget:self action: @selector(myaction:) forControlEvents :UIControlEventTouchUpInside];
[self.view addSubView:button];

}

所有其他链接到一个动作的按钮称为:

-(IBAction)myaction:(id)sender {
switch([sender tag])
case 1:
//open puzzle 1
break;
case 2:
//open puzzle 2
break;
...
default:
break;
}

【讨论】:

    【解决方案2】:

    这样的事情可能会奏效:

    - (void) viewDidLoad
    {
    
    for ( UIView* potentialButton in view.subviews )
    {
      if ( [potentialButton isKindOfClass: [UIButton class]] )
      {
         UIButton* actualButton = (UIButton*) potentialButton;
         [actualButton addTarget: self action: @selector( onButtonPress: ) forControlEvents: UIControlEventTouchUpInside];
       }
    }
    
    ...
    
    }
    
    - (void) onButtonPress: (UIButton*) sender
    {
      // determine which button here, by tag, or perhaps by button title, etc.
    }
    

    【讨论】:

    • 是的,我最终就是这么做的!
    【解决方案3】:

    您可以列出视图中的对象(子视图)以查找所有按钮。当然,您需要以某种方式清除其他对象。

    您可以为按钮执行 addTarget 以设置其操作方法。

    每个操作方法都接收一个指向 UI 对象的指针。您只需将指针与您的对象列表进行比较即可确定它是哪一个。

    【讨论】:

    • 或者控件的标签属性可以用于此目的
    【解决方案4】:

    Interface Builder 将允许您将 80 个对象连接到 1 个方法,我认为您可以通过多项选择一次完成所有操作(我会仔细检查。)然后,在该方法中,您可以使用 ( id)sender 值来确定它是哪个按钮;例如,通过说

    if([[[(UIButton*)sender titleLabel] text] isEqualToString:@"Puzzle 1"]){
        // open puzzle 1
    }
    

    如果你的标题是连续的,你可以遍历它们:

    NSString* senderTitle =  [[(UIButton*)sender titleLabel] text];
    
    for(int i=1; i<=80; i++){
        if([senderTitle isEqualToString:[NSString stringWithFormat:@"Puzzle %d",i]]){
             // open puzzle i
        }
    }
    

    【讨论】:

    • 哎呀 - 我刚刚检查过 - 你不能使用 Interface Builder 添加多个发件人。但是,正如其他答案所指出的那样,您可以在 viewDidLoad 和 addTarget: 中循环遍历它们。 [obj addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside];`
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2018-09-03
    • 2015-08-21
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多