【问题标题】:Tag changes it value标签改变它的价值
【发布时间】:2015-02-16 16:25:26
【问题描述】:

我不明白为什么标签第三次等于 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


}

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

【问题讨论】:

  • 对不起,b1 在顶部,我只是失败了。那么如果 B1 是一个全局变量,它好吗?而且我不明白问题c:三个按钮绑定一个动作,我尝试区分用户按下了哪个按钮,为此,我使用他们的标签。
  • 如果你有三个不同的按钮都调用同一个动作方法,你可以(a)给三个视图单独的tag值和(b)查看sender参数,这将参考哪个按钮被按下。在回答您的问题时,如果它确实是全局变量,那可能不是一个好主意。如果每个按钮都有单独的类的实例变量(或者更好的是一个属性),那么如果您需要保留对它的引用以供将来使用,那很好。
  • 是的,我别无选择,我让我做一个财产。感谢您的帮助。现在好了。

标签: objective-c uibutton tags


【解决方案1】:

当你这样做时:

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
}

【讨论】:

  • 但是如果我不写,按钮就不会出现
【解决方案2】:

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

funcA 中,您正在实例化一个完全不同的按钮(不是用户按下的按钮,也不是在viewDidLoad 中创建和丢弃的按钮)。您也永远不会为这个新按钮设置tag。 (坦率地说,根本不清楚funcA 是什么;你的故事板上有按钮或类似的东西吗?!?)

底线,如果您想让funcB 显示您在funcA 中创建的按钮的tag,那么您必须为funk 中的按钮设置tag


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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-09
    • 1970-01-01
    • 2011-08-15
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    相关资源
    最近更新 更多