gpt4 book ai didi

ios - UITextView 点击行尾不应在下一行返回单词

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:12:56 33 4
gpt4 key购买 nike

我正在尝试在点击 UITextView 中的特定单词(不可编辑)时进行继续 - 想象一下 Instagram 或 Twitter 移动应用程序中的主题标签或提及。

This post帮助我了解如何识别 UITextView 中特定单词的点击:

- (void)viewDidLoad
{
[super viewDidLoad];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(printWordSelected:)];
[self.textView addGestureRecognizer:tap];
}

- (IBAction)printWordSelected:(id)sender
{
NSLog(@"Clicked");

CGPoint pos = [sender locationInView:self.textView];
NSLog(@"Tap Gesture Coordinates: %.2f %.2f", pos.x, pos.y);

//get location in text from textposition at point
UITextPosition *tapPos = [self.textView closestPositionToPoint:pos];

//fetch the word at this position (or nil, if not available)
UITextRange * wr = [self.textView.tokenizer rangeEnclosingPosition:tapPos
withGranularity:UITextGranularityWord
inDirection:UITextLayoutDirectionRight];

NSLog(@"WORD: %@", [self.textView textInRange:wr]);
}

不幸的是,这种方法不是防弹的,并且报告在行尾的空格上的点击与在下一行开头的单词上的点击一样。

显然,这是 UITextView 中自动换行的结果,有时会将单词移动到下一行的开头。

  1. 有没有办法解决这个问题,而不是将行尾的这些点击报告为对换行符的点击?
  2. 是否有更好的方法来根据用户点击 UITextView 中的特定单词进行继续?

最佳答案

一个简单的解决方案是只返回两个方向(左和右)相同的单词。但是,这种方法有一个局限性。您将无法选择单字符词。

- (IBAction)printWordSelected:(id)sender
{
CGPoint pos = [sender locationInView:self.textView];

//get location in text from textposition at point
UITextPosition *tapPos = [self.textView closestPositionToPoint:pos];

//fetch the word at this position (or nil, if not available)
UITextRange * wr = [self.textView.tokenizer rangeEnclosingPosition:tapPos
withGranularity:UITextGranularityWord
inDirection:UITextLayoutDirectionRight];

//fetch the word at this position (or nil, if not available)
UITextRange * wl = [self.textView.tokenizer rangeEnclosingPosition:tapPos
withGranularity:UITextGranularityWord
inDirection:UITextLayoutDirectionLeft];


if ([wr isEqual:wl]) {

NSLog(@"WORD: %@", [self.textView textInRange:wr]);
}
}

关于ios - UITextView 点击行尾不应在下一行返回单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17530479/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com