I’m using the following code from Apple’s SimpleTextInput example to determine the frame for the cursor. I am using CTFrameGetLineOrigins and I noticed the y value it’s returning for it is incorrect (it displays .336 no matter which line is at). My app is a little different than the SimpleTextInput in that I’m vertically centering my text so the text frame isn’t starting directly at the origin. But still, why is it giving me this value for everyline? Is this a bug?
for (int i = 0; i < [lines count]; i++)
{
CTLineRef line = (CTLineRef) [lines objectAtIndex:i];
CFRange range = CTLineGetStringRange(line);
NSInteger localIndex = index - range.location;
if (localIndex >= 0 && localIndex <= range.length)
{
CGPoint origin;
CGFloat ascent, descent;
CTLineGetTypographicBounds(line, &ascent, &descent, NULL);
CTFrameGetLineOrigins(self.textFrame, CFRangeMake(i, 0), &origin);
CGFloat xPos = origin.x + CTLineGetOffsetForStringIndex(line, index, NULL);
return CGRectMake(xPos, origin.y - descent, 3, ascent + descent);
}
}
- (void) drawRect:(CGRect)rect
{
CTFramesetterRef textFramesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)self.text);
CGMutablePathRef textFrameMutablePath = CGPathCreateMutable();
CGPathAddRect(textFrameMutablePath, NULL, self.bounds);
self.textFrame = CTFramesetterCreateFrame(textFramesetter, CFRangeMake(0, 0), textFrameMutablePath, NULL);
CGFloat textFrameHeight = [self calculateHeightForTextFrame];
CGRect textFrameRect = CGRectMake(0, (self.bounds.size.height / 2) - (textFrameHeight / 2), self.bounds.size.width, textFrameHeight);
CGPathRelease(textFrameMutablePath);
textFrameMutablePath = NULL;
CFRelease(self.textFrame);
self.textFrame = NULL;
textFrameMutablePath = CGPathCreateMutable();
CGPathAddRect(textFrameMutablePath, NULL, textFrameRect);
self.textFrame = CTFramesetterCreateFrame(textFramesetter, CFRangeMake(0, 0), textFrameMutablePath, NULL);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CTFrameDraw(self.textFrame, context);
CGPathRelease(textFrameMutablePath);
CFRelease(textFramesetter);
[self cursorPositionChanged];
}
Oddly enough I seem to have fixed this problem by replacing:
with
No clue why but it works.