我动态创建了视图,在动态创建的按钮内部。单击按钮我必须同时获取视图和按钮的标签。 我已将代码用作
-(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);
}
有时候控件会按下按钮,有时会看到触摸。我必须同时获得两个标签。 提前致谢
答案 0 :(得分:4)
当您添加如下子视图时:
[numberView addSubview:numberButton];
numberButton
成为numberView
的子视图; numberView
也成为numberButton
的超级视图。您可以通过该属性访问它。
-(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);
}
答案 1 :(得分:0)
通常,您只会在一个地方捕捉用户的触摸,而不是像您尝试的那样捕捉两个用户。你可以在这里完全放弃GestureRecognizer,只需使用按钮的触摸事件。
然后你有几个选项来完成你想要的下一个位。在按钮的触摸处理程序中,在上面的情况下“按下”,您可以获得sender.tag(即按钮)和sender.superview.tag(视图)。
或者,您可以使用公式并只使用一个标记。例如,(view.tag * 1000)+(button.tag)。这意味着第一个视图上的第一个按钮的标签为1001. 1000代表视图,1代表按钮。第五个视图上的第八个按钮是5008.你只需要做一些简单的数学运算来提取原始数字。