标签会更改它的值

时间:2015-02-16 16:25:26

标签: objective-c uibutton tags

我不明白为什么标签第三次等于0。

UIButton *b1;
 - (void)viewDidLoad
{
    b1 =[[UIButton alloc] init];
    b1.tag = 1;
    NSLog(@"Button pressed: %d", b1.tag); // tag = 1
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}
- (void)funcA:(id)sender // I create mannualy the button b1
{
    NSLog(@"Button pressed 2nd: %d", b1.tag); // tag = 1
    b1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
b1.frame = CGRectMake(50, 50, 50, 50);
[b1 setTitle:@"b1" forState:UIControlStateNormal];
[self.view addSubview:b1];
[b1 addTarget:self action:@selector(funcB:) forControlEvents:UIControlEventTouchUpInside ];

}
-(void)funcB:(id)sender //the func of B1
{
    NSLog(@"Button 3rd %d", b1.tag); // here the tag = 0


}

我希望我所要求的是可能的。 ^^

2 个答案:

答案 0 :(得分:0)

当你这样做时:

b1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];

你正在制作一个新按钮。

您可以更改代码:

UIButton *b1;
- (void)viewDidLoad
{
  [super viewDidLoad];
  b1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  b1.tag = 1;
  b1.frame = CGRectMake(50, 50, 50, 50);
  [b1 setTitle:@"b1" forState:UIControlStateNormal];

  NSLog(@"Button pressed: %d", b1.tag); // tag = 1
  // Do any additional setup after loading the view, typically from a     nib.
}
- (void)funcA:(id)sender // I create mannualy the button b1
{
  NSLog(@"Button pressed 2nd: %d", b1.tag); // tag = 1
  [b1 addTarget:self action:@selector(funcB:) forControlEvents:UIControlEventTouchUpInside ];
  [self.view addSubview:b1];

}
-(void)funcB:(id)sender //the func of B1
{
   NSLog(@"Button 3rd %d", b1.tag); // here the tag = 1
}

答案 1 :(得分:0)

viewDidLoad中,您正在创建一个按钮,但不是将其保存在任何位置(您没有使用b1实例变量,而是拥有一个巧合地具有名称的局部变量)和不将它添加到任何视图,因此它将在函数完成时释放。

funcA中,您将实例化一个完全不同的按钮(不是用户按下的按钮,而不是viewDidLoad中创建和丢弃的按钮)。您也从未为此新按钮设置tag。 (坦率地说,目前还不清楚是什么叫funcA;你的故事板上有一个按钮或类似的东西吗?!?)

下划线,如果您希望funcB显示您在tag中创建的按钮的funcA,则必须在tag中为该按钮设置funk {1}}。


funcB中,引用sender来识别按下哪个按钮很有用,例如:

- (void)createButton
{
    b1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    b1.frame = CGRectMake(50, 50, 50, 50);
    b1.tag = 42;
    [b1 setTitle:@"b1" forState:UIControlStateNormal];
    [self.view addSubview:b1];
    [b1 addTarget:self action:@selector(funcB:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)funcB:(UIButton *)sender
{
    NSLog(@"Button tag %d", sender.tag);  // the answer is 42
}