我需要能够可靠地获取Core Text框架中的tapped字符的索引。我有这个代码,它可靠地获取正确的行,但在抽头索引上从零到2个字符。错误永远是前进的;也就是说,它在正确的索引之前获得索引1到2个字符。在长段的开头,它通常偏离2个字符;到最后,它通常是正确的。我的文本是属于字符串的希腊文字,不确定这是否有所不同。
非常感谢任何帮助。
感谢。
- (void)receivedTap:(UITapGestureRecognizer*)recognizer
{
CGAffineTransform transform = CGAffineTransformMake(1, 0, 0, -1, 0, self.bounds.size.height);
CGPoint point = CGPointApplyAffineTransform([recognizer locationInView:self], transform);
// Getting all CTLines
CFArrayRef lines = CTFrameGetLines(textFrame);
CFIndex countOfLines = CFArrayGetCount(lines);
int lineNumber = 0;
for ( CFIndex i = 0; i < countOfLines; i++ ) // For each CTLine
{
CTLineRef line = CFArrayGetValueAtIndex(lines, i);
CGRect lineRect = CGRectZero;
CGFloat ascent = 0, descent = 0;
// Calculating CTLine frame
CTFrameGetLineOrigins(textFrame, CFRangeMake(i, 1), &lineRect.origin);
lineRect.size.width = CTLineGetTypographicBounds(line, &ascent, &descent, NULL);
lineRect.size.width -= CTLineGetTrailingWhitespaceWidth(line);
lineRect.size.height = ascent + descent;
lineRect.origin.y -= descent;
lineRect = CGRectIntegral(lineRect);
if ( ! CGRectContainsPoint(lineRect, point) ) {
lineNumber++;
continue;
}
NSLog(@"line is %d", lineNumber);
CFIndex touchedIndex = CTLineGetStringIndexForPosition(line, point);
NSInteger touchedIndexInt = (NSInteger)touchedIndex;
NSLog(@"found it : char %d", touchedIndexInt);
break;
}
答案 0 :(得分:1)
您是否尝试将其放在UITextView中并执行类似
的操作 UITextPosition *touchPosition = [self.textView closestPositionToPoint:point];
UITextRange *touchRange = [self.textView.tokenizer rangeEnclosingPosition:touchPosition withGranularity:UITextGranularityCharacter inDirection:UITextLayoutDirectionRight];
NSLog(@"%@",[self.textView textInRange: touchRange]);