从UITextView获取文本的来源

– 目标:在UITextView中获取文本的特定部分的来源

以下是我正在处理的应用程序的屏幕截图的链接。 请看,因为它更容易解释。 图片链接: ScreenShot

这是一个填补空白风格的游戏的开始。 我目前正在尝试获取每个下划线的x,y坐标。 当点击屏幕底部的一个单词时,它将移动到下一个可用的下划线空间。

目前我已经写了这个代码来做我所需要的,但是它非常难看,几乎没有工作,并且不是很灵活。 见下文:

// self.mainTextView is where the text with the underscores is coming from NSString *text = self.mainTextView.text; NSString *substring = [text substringToIndex:[text rangeOfString:@"__________"].location]; CGSize size = [substring sizeWithFont:self.mainTextView.font]; CGPoint p = CGPointMake((int)size.width % (int)self.mainTextView.frame.size.width, ((int)size.width / (int)self.mainTextView.frame.size.width) * size.height); // What is going on here is for some reason everytime there is a new // line my x coordinate is offset by what seems to be 10 pixels... // So was my ugly fix for it.. // The UITextView width is 280 CGRect mainTextFrame = [self.mainTextView frame]; px = px + mainTextFrame.origin.x + 9; if ((int)size.width > 280) { NSLog(@"width: 280"); px = px + mainTextFrame.origin.x + 10; } if ((int)size.width > 560) { NSLog(@"width: 560"); px = px + mainTextFrame.origin.x + 12; } if ((int)size.width > 840) { px = px + mainTextFrame.origin.x + 14; } py = py + mainTextFrame.origin.y + 5; // Sender is the button that was pressed newFrame = [sender frame]; newFrame.origin = p; [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionAllowAnimatedContent|UIViewAnimationCurveEaseInOut animations:^{ [sender setFrame:newFrame]; } completion:^(BOOL finished){ } ]; 

所以对我来说最好的问题是什么是更好的方法去做这个? 或者你有什么build议? 你会怎么做呢?

预先感谢您的时间。

而不是手动search每个下划线的出现。 利用NSRegularExpression这使得你的任务如此简单和容易。 find匹配的string后,利用NSTextCheckingResult获取每个匹配string的位置。

More Explaination:

您可以使用正则expression式来获取下划线的所有出现。这是使用下面的代码obonied。

 NSError *error = NULL; NSString *pattern = @"_*_"; // pattern to search underscore. NSString *string = self.textView.text; NSRange range = NSMakeRange(0, string.length); NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error]; NSArray *matches = [regex matchesInString:string options:NSMatchingProgress range:range]; 

一旦你得到所有的匹配模式,你可以使用下面的代码获取匹配的string的位置。

 [matches enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { if ([obj isKindOfClass:[NSTextCheckingResult class]]) { NSTextCheckingResult *match = (NSTextCheckingResult *)obj; CGRect rect = [self frameOfTextRange:match.range inTextView:self.textView]; //get location of all the matched strings. } }]; 

希望这能解答你所有的担忧!