【问题标题】:How to identify which button is clicked in Objective-C?如何识别在 Objective-C 中单击了哪个按钮?
【发布时间】:2012-05-23 16:10:53
【问题描述】:

我是一名新的 iPad 开发者。

我以编程方式创建了 UIButton,我想在其中识别用户点击了哪个按钮,并据此执行一些操作。

我应该如何识别这个?

这是我的代码 sn-p:

for(int i=0;i<[_array count];i++)
    {

        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        button.tag=count;
        [button addTarget:self 
                   action:@selector(aMethod:)
         forControlEvents:UIControlEventTouchDown];

        button.backgroundColor=[UIColor redColor];
        [button setTitle:@"Show View" forState:UIControlStateNormal];
        button.frame = CGRectMake(xpos, 270.0, 200.0, 150.0);

        [self.view addSubview:button];            
    }

这就是我现在正在做的事情:我想我会为每个按钮分配计数,然后我会将这个计数传递给按钮单击方法。这是一个好主意吗?有没有其他办法?

点击按钮我正在呼叫aMethod:

-(void)aMethod:(id)sender{
    NSLog(@"btn clicked");

}

任何帮助将不胜感激!

【问题讨论】:

  • 你的逻辑和想法没有错。您可以在按钮中访问tag 以区分彼此。是的,我可以说,这是个好主意。我的项目也是这样做的。

标签: iphone ios ipad uibutton sender


【解决方案1】:
-(void)aMethod:(UIButton*)sender{
    NSLog(@"btn clicked %d", sender.tag);

}

【讨论】:

  • 是的,您可以使用按钮的标签来识别按下了哪个按钮。
  • 我会这样做。我相信使用 tag 属性是识别按钮的标准方法。
猜你喜欢
  • 2018-05-15
  • 2021-04-25
  • 1970-01-01
  • 2017-07-24
  • 2014-01-05
  • 1970-01-01
  • 2012-08-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多