开发者

How can I use CoreText to bold text?

开发者 https://www.devze.com 2023-04-01 22:49 出处:网络
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.

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").

  1. Create a CTFont Object using the bold font of your choice.
  2. Use addAttribute:value:range: method of your NSAttributedString, pass "kCTFontAttributeName" for the first parameter and your CTFont object for the second.
  3. 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) .
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号