2

在我的应用程序的一个视图控制器上,有一长串以编程方式添加的大约 20 个按钮,我想调用相同的方法,但要通过它们的按钮标签来识别自己,但我遇到了一个让我退缩的问题几个小时的研究和尝试。基本问题是我不太清楚如何以除了初始化它们的方法之外的任何其他方法访问以编程方式创建的按钮。

我的问题总结了:

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

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

这是我到目前为止的代码,但它产生的错误将在下面解释。

-(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'"
}
}
4

2 回答 2

3

我们不是在神秘的红宝石领域工作,需要初始化并存储在某个地方以便您调用它们,试试这个:

#.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;
}

注意:我是凭记忆做的,所以它可能无法完美运行。

于 2012-12-15T03:45:32.533 回答
2
#.h
@interface MyController : UIViewController{
   UIButton *buttons;
}

#.m

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

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

-(void)itemSelected
 { 
      if ([sender tag] == 1) 
      {  
        self.button.hidden = YES;
      }
  }
于 2012-12-15T03:49:37.430 回答