I'm making a magazine with Core Text and I'm trying to automatically add hyphens to the text. I think I can do this with the function
CFStringGetHyphenationLocationBeforeIndex
But it's not working and I can't find any examples online.
What I'm trying to do is setting up the text and if I find any hyphen position I put a "-" there and replace the text via the accessor so it calls setNeedsDisplay and draws again from scratch.
- (void) setTexto:(NSAttributedString *)texto {
_texto = texto;
if (self.ctFrame != NULL) {
CFRelease(self.ctFrame);
self.ctFrame = NULL;
}
[self setNeedsDisplay];
}
-(void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextScaleCTM(context, 1.0, -1.0);
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, self.bounds);
CTFramesetterRef ctFrameSetterRef = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)(_texto));
self.ctFrame = CTFramesetterCreateFrame(ctFrameSetterRef, CFRangeMake(0, [_texto length]), path, NULL);
NSArray *lines = (__bridge NSArray *)(CTFrameGetLines(self.ctFrame));
CFIndex lineCount = [lines count];
NSLog(@"lines: %d", lines.count);
for(CFIndex idx = 0; idx < lineCount; idx++) {
CTLineRef line = CFArrayGetValueAtIndex((CFArrayRef)lines, idx);
CFRange lineStringRange = CTLineGetStringRange(line);
NSRange lineRange = NSMakeRange(lineStringRange.location, lineStringRange.length);
NSString* lineString = [self.texto.string substringWithRange:lineRange];
CFStringRef localeIdent = CFSTR("es_ES");
CFLocaleRef localeRef = CFLocaleCreate(kCFAllocatorDefault, localeIdent);
NSUInteger breakAt = CFStringGetHyphenationLocationBeforeIndex((__bridge CFStringRef)lineString, lineRange.length, CFRangeMake(0, lineRange.length), 0, localeRef, NULL);
if(breakAt!=-1) {
NSRange replaceRange = NSMakeRange(lineRange.location+breakAt, 0);
NSMutableAttributedString* attributedString = self.texto.mutableCopy;
[attributedString replaceCharactersInRange:replaceRange withAttributedString:[[NSAttributedString alloc] initWithString:@"-"]];
self.texto = attributedString.copy;
break;
} else {
CGFloat ascent;
CGFloat descent;
CTLineGetTypographicBounds(line, &ascent, &descent, nil);
CGContextSetTextPosition(context, 0.0, idx*-(ascent - 1 + descent)-ascent);
CTLineDraw(line, context);
}
}
}
The problem is the second time it goes into drawRect (with the new text) lines.count log to 0. And also I'm not sure this is the correct way to do it.
Maybe there's another way to modify the CTLines (adding the remaining characters after the "-" from the previous line).