用于 UILabel 问题的 UITapGesture 选择器
Posted
技术标签:
【中文标题】用于 UILabel 问题的 UITapGesture 选择器【英文标题】:UITapGesture Selector for UILabel issue 【发布时间】:2017-03-20 09:54:16 【问题描述】:我为 self.view 和 UILabel(mainView 的子视图)添加了 tapGesture,每个执行不同的选择器。
但是唯一的主视图 tapGesture 被调用并且标签 tapgesture 没有被调用。如何处理?
代码如下:
UITapGestureRecognizer *tapGesForSelf = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesForSelf:)];
[self.view addGestureRecognizer:tapGesForSelf];
UITapGestureRecognizer *tapLblClick = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesForLbl:)];
[lbl addGestureRecognizer:tapLblClick];
对于两个选择器,只有一种方法称为 tapGesForSelf。 这里 lbl 是 self.view 的子视图。
【问题讨论】:
你能分享你的代码吗? 使用 UIButton 代替标签并定义其选择器操作。 How to get UILabel to respond to tap?的可能重复 您是否启用了标签的用户交互?? 是的,它已启用。 【参考方案1】:试试这个
- (void)viewDidLoad
[super viewDidLoad];
[_lbl setUserInteractionEnabled:YES];
UITapGestureRecognizer *tapGesForSelf = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesForSelf:)];
[self.view addGestureRecognizer:tapGesForSelf];
UITapGestureRecognizer *tapLblClick = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesForLbl:)];
[_lbl addGestureRecognizer:tapLblClick];
[tapGesForSelf requireGestureRecognizerToFail:tapLblClick];
- (void)tapGesForSelf:(UITapGestureRecognizer *)gesture
NSLog(@"self");
- (void)tapGesForLbl:(UITapGestureRecognizer *)gesture
NSLog(@"label");
【讨论】:
【参考方案2】:一旦我尝试过并且效果很好,我现在就发布你的问题的答案。
首先在设计中看到标签。我将标签文本设置为“Tap Me”
现在我为视图和标签设置代码
- (void)viewDidLoad
[super viewDidLoad];
//TapGesture for Label
UITapGestureRecognizer *tapLabel = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionTapLabel:)];
tapLabel.delegate = self;
tapLabel.numberOfTapsRequired = 1;
lblTapMe.userInteractionEnabled = YES;
[lblTapMe addGestureRecognizer:tapLabel];
//TapGesture for View
UITapGestureRecognizer *tapMainView = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionTapMainView:)];
tapMainView.delegate = self;
tapMainView.numberOfTapsRequired = 1;
[self.view addGestureRecognizer:tapMainView];
//Action method for Label
-(void)actionTapLabel:(UITapGestureRecognizer *)gestureOnLabel
UILabel *label = (UILabel *)gestureOnLabel.view;
NSLog(@"Lable text is - %@",label.text);
//Action method for View
-(void)actionTapMainView:(UITapGestureRecognizer *)gestureOnMainView
NSLog(@"The Main view is tapped");
输出截图
【讨论】:
【参考方案3】:请设置UserInteractionEnabled:YES 用于与TapGesture 交互
[lbl setUserInteractionEnabled:YES];
【讨论】:
以上是关于用于 UILabel 问题的 UITapGesture 选择器的主要内容,如果未能解决你的问题,请参考以下文章
AutoLayout 适用于 UIView 但不适用于 UILabel。为啥?
UITableHeaderView 自动布局中的 UILabel 不适用于 iPhone 6
UITapGestureRecognizer 适用于 UIImageView 但不适用于 UILabel