How can I use CoreText to bold text?
I am modifying a class that I found. It is underlining hyperlinks. I would like it to bold the hyperlink as well. I am not sure how to do this with CoreText.
-(NSMutableAttributedString*)attributedTextWithLinks {
NSMutableAttributedString* str = [self.attributedText mutableCopy];
if (!str) return nil;
if (self.automaticallyDetectLinks) {
NSError* error = nil;
NSDataDetector* linkDetector = [NSDataDet开发者_如何学JAVAector dataDetectorWithTypes:NSTextCheckingTypeLink error:&error];
[linkDetector enumerateMatchesInString:[str string] options:0 range:NSMakeRange(0,[[str string] length])
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop)
{
int32_t uStyle = self.underlineLinks ? kCTUnderlineStyleSingle : kCTUnderlineStyleNone;
UIColor* thisLinkColor = (delegate && [delegate respondsToSelector:@selector(colorForLink:underlineStyle:)])
? [delegate colorForLink:result underlineStyle:&uStyle] : self.linkColor;
if (thisLinkColor)
[str setTextColor:thisLinkColor range:[result range]];
if (uStyle>0)
[str setTextUnderlineStyle:uStyle range:[result range]];
}];
}
[customLinks enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
NSTextCheckingResult* result = (NSTextCheckingResult*)obj;
int32_t uStyle = self.underlineLinks ? kCTUnderlineStyleSingle : kCTUnderlineStyleNone;
UIColor* thisLinkColor = (delegate && [delegate respondsToSelector:@selector(colorForLink:underlineStyle:)])
? [delegate colorForLink:result underlineStyle:&uStyle] : self.linkColor;
if (thisLinkColor)
[str setTextColor:thisLinkColor range:[result range]];
if (uStyle>0)
[str setTextUnderlineStyle:uStyle range:[result range]];
}];
return [str autorelease];
}
You need to set the font to a "Bold" font (e.g. "Helvetica" and "Helvetica-Bold").
- Create a CTFont Object using the bold font of your choice.
- Use
addAttribute:value:range:
method of your NSAttributedString, pass "kCTFontAttributeName" for the first parameter and your CTFont object for the second. - To avoid leaks remember to release the CTFont object if it was created by a method that has "create" in its name; use
CFRelease(CFType obj)
.
精彩评论