将 TapGestureRecogniser 添加到 UITextView
Posted
技术标签:
【中文标题】将 TapGestureRecogniser 添加到 UITextView【英文标题】:Add TapGestureRecogniser to UITextView 【发布时间】:2016-01-27 13:32:47 【问题描述】:我查看了类似的问题并尝试了答案,但我无法让它们发挥作用,所以如果这是一个重复的问题,我们深表歉意。
我的表格视图中有两个地址字段,它们在静态单元格中动态添加。当用户在第一个框中输入地址时,我希望在他们单击第二个地址字段时出现“复制地址”的问题,如果他们回答“是”则复制地址。我在 tableView didSelectRowAtIndexPath 上有这个工作,但是当用户直接点击字段中的 UITextView 时它不起作用。我尝试将以下内容添加到 viewDidLoad() 函数中:
UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
[self.billingAddress addGestureRecognizer:tap];
但是当点击 UITextView billingAddress 时,以下代码不会触发。
- (void)handleTap:(UITapGestureRecognizer *)recognizer
NSLog(@"I am here");
我应该注意到 billingAddress 被定义为 UITextField 属性,并从静态单元格中分配了 tableView cellForRowAtIndexPath 中的单元格详细信息。这是使用以下代码完成的:
if (section == 0 && row == 3)
BFCell* cell = [self.tableView dequeueReusableCellWithIdentifier:@"CheckoutInputCell"];
cell.nameLabel.text = @"Billing Address";
cell.nameLabel.font = [UIFont fontWithName:@"Populaire" size:23.0f];
cell.textField.placeholder = @"Required";
self.billingAddress = cell.textField;
cell.textField.keyboardType = UIKeyboardTypeAlphabet;
return cell;
我想知道我是否将点击手势分配到了错误的位置,它应该分配给 cell.textField。对此的任何帮助将不胜感激。
【问题讨论】:
【参考方案1】:我认为发生的是文本字段和手势识别器之间的冲突。我会使用 UITextFieldDelegate
textFieldShouldBeginEditing:
来检测用户何时点击文本字段。
【讨论】:
【参考方案2】:持有属于UITableViewCell
的对象的引用是一个大错误。
最好将UITapGestureRecognizer
直接添加到单元格内的文本字段中,当单元格中有一个布尔标记来告诉它是否应该响应触摸时。
if (section == 0 && row == 3)
BFCell* cell = [self.tableView dequeueReusableCellWithIdentifier:@"CheckoutInputCell"];
cell.nameLabel.text = @"Billing Address";
cell.nameLabel.font = [UIFont fontWithName:@"Populaire" size:23.0f];
cell.textField.placeholder = @"Required";
//self.billingAddress = cell.textField; // wrong way.
cell.addTouchFlag = true // do this instead.
cell.textField.keyboardType = UIKeyboardTypeAlphabet;
return cell;
两者都有
UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
[self.textField addGestureRecognizer:tap];
和
- (void)handleTap:(UITapGestureRecognizer *)recognizer
NSLog(@"I am here");
应该在 cell 类中(如果你没有,你应该创建它)。
更新: 在Charles Thierry answer 中,他有一个很好的观点,即使用委托方法是检测文本字段内的用户点击的更好方法。但是您应该按照我上面提到的方式进行操作。这意味着单元类将符合UITextFieldDelegate
并实现textFieldShouldBeginEditing:
【讨论】:
以上是关于将 TapGestureRecogniser 添加到 UITextView的主要内容,如果未能解决你的问题,请参考以下文章
如何将 Groups 添加到 ListView,然后将 Items 添加到 Groups