如何查看以编程方式创建的UIButton的标签 [英] How to see the tag of a programmatically created UIButton

查看:77
本文介绍了如何查看以编程方式创建的UIButton的标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序的一个viewController上,有一长串的列表以编程方式添加了20个左右的按钮,所有这些我都想调用相同的方法,但是要通过它们的button标记来标识自己,但是我遇到了一个已设置的问题我花了数小时的时间进行研究和尝试.基本问题是我不知道如何使用除初始化方法之外的任何其他方法访问以编程方式创建的按钮.

on one viewController of my app there is a long list of 20 or so buttons added programmatically, all which i want to call the same method, but to identify themselves through their button tag, but i ran into a problem that has set me back a few hours of research and attempts.The basic problem is i dont quite know how to access a programmatically created button in any other method than the method that they were initialized in.

我的问题总结如下:

1)如果我要在viewDidLoad方法中创建按钮,如何在我创建的void方法中访问它?

1) if i were to create the button in the viewDidLoad method, how can I access it in a void method that i create?

2)如何在创建的void方法中访问那些按钮标签?

2) How can i access those button tags in the created void method?

这是我到目前为止所拥有的代码,但是它会产生错误,下面将作详细解释.

Here is the code that i have so far, but it is producing errors that ill explain below.

-(void)viewDidLoad{
float itemScrollerXdirection =0;
float itemScrollerYdirection =0;
float ySize =70.0;
float xSize = 70.0;

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(itemScrollerXdirection,itemScrollerYdirection,xSize,ySize);
[button addTarget:self action:@selector(itemSelected) forControlEvents:UIControlEventTouchUpInside];
button.tag =1;
[button setTitle:@"button1" forState:UIControlStateNormal];
[itemScroller addSubview:button];
}
//no errors in the above code

-(void)itemSelected{


if ([sender tag] == 1) {  //Gets error "Use of undeclaired identifier 'sender'"
    button.hidden = YES; //Gets error "Use of undeclaired identifier 'button1'"
}
}

推荐答案

我们不在红宝石神秘的世界里工作,需要初始化事物并将其存储在某个地方以便您调用它们,请尝试以下操作:

We aren't working in the mystical relm of ruby, things need to be initialized and stored somewhere inorder for you to call them, try this:

#.h
@interface MyController : UIViewController{
   NSMutableArray *buttons;
}

#.m
-(void)init // Or whatever you use for init
{
   buttons = [[NSMutableArray alloc] init];
}

-(void)viewDidLoad{
  //blah blah (what you already have)

  [button addTarget:self action:@selector(itemSelected:)     //Add ":"
               forControlEvents:UIControlEventTouchUpInside];
  button.tag =0;

  [buttons addObject:button] //Add button to array of buttons

  //blah blah (what you already have)
}

-(IBAction)itemSelected:(id)sender{
   UIButton* button = [buttons objectAtIndex:sender.tag]
   button.hidden = YES;
}

注意:我是从内存开始执行此操作的,因此它可能无法完美运行.

Note: I'm doing this from memory on, so it might not work perfectly.

这篇关于如何查看以编程方式创建的UIButton的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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