从循环中识别UIButton [英] Recognizing UIButton from a loop

查看:48
本文介绍了从循环中识别UIButton的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到一个问题/答案,其结果与我正在寻找的结果类似,但是所讨论的代码比我现在要复杂得多.

I've seen one question/answer with a result similar to what I'm looking for, but the code discussed was much more complicated than I have right now.

我正在使用for()循环从数组创建一堆按钮.然后,我有一个动作,但是我无法识别该按钮.所以:

I'm using a for() loop to create a bunch of a buttons from an array. Then, I have an action, but I'm unable to recognize the button. So:

NSArray *numbers = [NSArray arrayWithOjbects:@"1", "2", "3", nil];

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

   button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
   [button addTarget:self action:@selector(recognize:) forControlEvents:UIControlEventTouchDown];
   [button setTitle:[numbers objectAtIndex:i] forState:UIControlStateNormal];
   button.frame = CGRectMake(x, y, w, l);

   }

然后:

-(void) recognize:(id)sender {

   NSLog (button.titleLabel.text);

 }

但是,无论按下什么按钮,我都只会得到数组(3)的最后一个成员.我想我在-(无效)识别:(id)发件人中缺少一个步骤...我应该知道...但是它现在完全在逃避我.

But, I only get the last member of the array (3) regardless of button pressed. I think I'm missing a step in -(void) recognize:(id)sender... that I should be know... but it's completely escaping me right now.

/弗拉德

推荐答案

循环的每次迭代都分配给 button 变量.退出循环后,它将仅保留您分配给它的最后一个值. button 变量似乎是一个实例变量-它是类实例的唯一变量,而不是按钮的唯一变量.

Each iteration of the loop assigns to the button variable. When the loop is exited, it will simply hold the last value you assigned to it. The button variable appears to be an instance variable - it's unique to the instance of the class, not to the button.

执行所需操作的便捷方法是访问 sender 变量,iOS为您的方法提供了该变量.这将保存产生问题的对象,在本例中为按钮.

The convenient way of doing what you want is to access the sender variable, which iOS supplies to your method. This holds the object that produced the event in question, in this case, the button.

NSLog (@"%@", ((UIButton *)sender).titleLabel.text);

还请注意,以这种方式记录文本值是不可接受的.如果它包含格式字符串(例如%@ ),则它将期望另一个参数,该参数不会获取,并且会崩溃.这可能是一个安全漏洞.当您有要记录的字符串变量时,请使用%@ 进行记录,如上所述.Xcode应该已经在警告您这一点.不要忽略警告.

Also note that it's not acceptable to log a text value in that way. If it contains a format string (such as %@), it will expect a further argument, which it doesn't get, and will crash. This can be a security hole. When you have a string variable that you want to log, use %@ to log it, as above. Xcode should already be warning you about this. Do not ignore warnings.

这篇关于从循环中识别UIButton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆