iOS7:UITapGestureRecognizer 重用问题
Posted
技术标签:
【中文标题】iOS7:UITapGestureRecognizer 重用问题【英文标题】:iOS7: UITapGestureRecognizer reuse issue 【发布时间】:2014-06-16 14:18:26 【问题描述】:我设置了三个按钮。每个按钮都标记为 1...3。
我的 UITapGestureRecognizer 只对第一个 UIButton 有效。无法选择其他两个选项。 代码:
- (void)viewDidLoad
[super viewDidLoad];
UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(buttonTapped:)];
recognizer.delegate = self;
recognizer.cancelsTouchesInView = NO;
[recognizer setNumberOfTapsRequired:1];
[_btnNegative addGestureRecognizer:recognizer];
[_btnNeutral addGestureRecognizer:recognizer];
[_btnPositive addGestureRecognizer:recognizer];
还有buttonTapped:
方法:
-(void)buttonTapped:(UITapGestureRecognizer *)recognizer
switch (((UIGestureRecognizer *)recognizer).view.tag)
case 1:
NSLog(@"Positive");
[_btnPositive setBackgroundImage:[UIImage imageNamed:@"checkedBox"] forState:UIControlStateNormal];
[_btnNegative setBackgroundImage:[UIImage imageNamed:@"UncheckedBox"] forState:UIControlStateNormal];
[_btnNeutral setBackgroundImage:[UIImage imageNamed:@"UncheckedBox"] forState:UIControlStateNormal];
_opinion=@"Positive";
break;
case 2:
NSLog(@"Negative");
[_btnNegative setBackgroundImage:[UIImage imageNamed:@"checkedBox"] forState:UIControlStateNormal];
[_btnPositive setBackgroundImage:[UIImage imageNamed:@"UncheckedBox"] forState:UIControlStateNormal];
[_btnNeutral setBackgroundImage:[UIImage imageNamed:@"UncheckedBox"] forState:UIControlStateNormal];
_opinion=@"Negative";
break;
case 3:
NSLog(@"Neutral");
[_btnNeutral setBackgroundImage:[UIImage imageNamed:@"checkedBox"] forState:UIControlStateNormal];
[_btnNegative setBackgroundImage:[UIImage imageNamed:@"UncheckedBox"] forState:UIControlStateNormal];
[_btnPositive setBackgroundImage:[UIImage imageNamed:@"UncheckedBox"] forState:UIControlStateNormal];
_opinion=@"Neutral";
break;
只有case:1
有效。其他情况永远不会被调用。我重新检查了按钮标签并确定 1...3。非常感谢您的帮助。
【问题讨论】:
【参考方案1】:不,您不能重复使用相同的手势识别器。手势识别器设计为附加到一个且仅一个视图。
【讨论】:
好的,我明白了。你能告诉我更优雅的方式来分配和初始化两个额外的识别器还是 Gal Marom 引入的代码是最优雅的? 创建按钮数组,调用循环数组的方法并向其添加新手势 假设所有手势识别器的配置方式都一样,Gai的方案是好的。【参考方案2】:我遇到了同样的问题 尝试为每个按钮分配一个新的 UITapGestureRecognizer:
UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(buttonTapped:)];
recognizer.delegate = self;
recognizer.cancelsTouchesInView = NO;
[recognizer setNumberOfTapsRequired:1];
[_btnNegative addGestureRecognizer:recognizer];
recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(buttonTapped:)];
[_btnNeutral addGestureRecognizer:recognizer];
recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(buttonTapped:)];
[_btnPositive addGestureRecognizer:recognizer];
【讨论】:
这肯定会奏效。我的问题实际上是我是否可以重用相同的手势识别器。肯定有办法的。 我很确定你不能 - 手势指的是视图,它是子视图。此外,通过添加相同的手势,您将获得什么?它也会以这种方式调用相同的目标和操作。 是的女孩。听起来不错。一个指针不能指向多个对象。 好的。谢谢你,盖尔。你的答案是完整的。我非常感谢。以上是关于iOS7:UITapGestureRecognizer 重用问题的主要内容,如果未能解决你的问题,请参考以下文章