iOS:同一个单词的Bold和Italic

Byt*_*yte 6 iphone xcode bold italic ios

背景:我一直试图用Bold和Italic字体以及普通字体显示一个句子.

问题:如何显示类似"Hello,我的名字是Byte "的内容.请注意,Byte既是粗体又是斜体,而其他单词仍然正常.

我试过了:我认为coreText应该能够做到这一点,我只是无法找到正确的方法来做到这一点.我也使用了TTTAttributeLabel,并且不能使它既粗体又斜体.我有Three20加载,只是不知道使用哪个或什么.Webview不适用于我的背景.


作为对Carles Estevadeordal的回复:

UIWebView *webView = [[UIWebView alloc]initWithFrame:CGRectMake(10, 360, 300, 40)];
[webView setBackgroundColor: [UIColor clearColor]];
[webView loadHTMLString:[NSString stringWithFormat:@"<html><body style=\"background-color: transparent;\">Hello, my name is <b><i>Byte</b></i></body></html>"] baseURL:nil];
[self.view addSubview:webView];
Run Code Online (Sandbox Code Playgroud)

这正是我用过的代码.它显示白色背景.

Byt*_*yte 7

经过一夜好眠,我找到了一种使用TTTAtributedlabel的方法.方法如下:

TTTAttributedLabel *attLabel = [[TTTAttributedLabel alloc]initWithFrame:CGRectMake(x, y, xx, yy)];
NSString *text = @"Hello, my name is Byte";

[attLabel setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:^(NSMutableAttributedString *mutableAttributedString) {

    //font helvetica with bold and italic 
    UIFont *boldSystemFont = [UIFont fontWithName:@"Helvetica-BoldOblique" size:10];

    CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)boldSystemFont.fontName, boldSystemFont.pointSize, NULL);

    NSRange boldRange = [[mutableAttributedString string] rangeOfString:@"Byte" options:NSCaseInsensitiveSearch];
    [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)font range:boldRange];

    CFRelease(font);

    return mutableAttributedString;
}];
Run Code Online (Sandbox Code Playgroud)

我仍然无法将2个属性(即:粗体和斜体)分别添加到同一个单词/字母中.但这就是诀窍.

  • @Byte即使是ARC,你仍然应该释放你创建的CTFont对象.例如:`CFRelease(font)` (2认同)