0

我已经动态创建了视图,在动态创建的按钮内部。单击按钮时,我必须同时获取视图和按钮的标签。我已将代码用作

-(void)addButton
{
    for (int j=0; j<[defaultNumberAry count]; j++) {

    numberButton=[[UIButton alloc]initWithFrame:CGRectMake(n, 0, 40, 40)];
    n=n+42;
    [numberButton setBackgroundImage:[defaultNumberAry objectAtIndex:j] forState:UIControlStateNormal];
    numberButton.tag=j;
    [numberTagAry addObject:[NSString stringWithFormat:@"%d",j]];
    numberButton.userInteractionEnabled = YES;
    [numberButton addTarget:self action:@selector(pressed:) forControlEvents:UIControlEventTouchUpInside];
    numberButton.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth;
    [numberView addSubview:numberButton];

}
}
-(void)addView:(int)yv
{
n=22;
numberView=[[UIView alloc]initWithFrame:CGRectMake(300, yv, 400, 44)];
numberView.backgroundColor=[UIColor yellowColor];
numberView.tag=b;
b++;
numberView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth;
UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touched:)];
[tapGestureRecognizer setNumberOfTapsRequired:1];
[numberView addGestureRecognizer:tapGestureRecognizer];

}
-(void)pressed:(id)sender{
    UIButton *button = (UIButton *)sender;
    if(!button.selected){
        NSLog(@"selected btn tag:%d",button.tag);       
                       }
}
- (void) touched:(id)sender
{
    int v=((UIGestureRecognizer *)sender).view.tag;
    NSLog(@"view tag:::%d",v);

  }

有时控件会按下按钮,有时会查看触摸。我必须一次获得两个标签。提前致谢

4

2 回答 2

5

当您像这样添加子视图时:

[numberView addSubview:numberButton];

numberButton成为;的子视图 numberViewnumberView成为的superviewnumberButton您可以通过该属性访问它。

-(void)pressed:(id)sender{
    UIButton *pressedButton = (UIButton *)sender;
    UIView *superViewOfPressedButton = pressedButton.superview;
    NSLog(@"Tag of button:%i Tag of pressed button's button view is %i",pressedButton.tag,superViewOfPressedButton.tag);
}
于 2012-04-24T05:28:34.203 回答
0

通常,您只会在一个地方捕获用户的触摸,而不是像您尝试做的两个地方。您可以在此处完全删除 GestureRecognizer,只需使用按钮的触摸事件。

然后你有几个选项来完成你想要的下一点。在按钮的触摸处理程序中,在上述情况下为“按下”,您可以获得作为按钮的 sender.tag 和作为视图的 sender.superview.tag。

或者,您可以使用公式并只使用一个标签。例如,(view.tag * 1000) + (button.tag)。所以这意味着第一个视图上的第一个按钮的标签为 1001。1000 代表视图,1 代表按钮。第五个视图上的第八个按钮是 5008。您只需做一些简单的数学运算即可提取原始数字。

于 2012-04-24T05:28:14.217 回答