这是我尝试的代码:

NSString *strFirst = [NSString stringWithFormat:@"The App feature is only available to users while at "];
NSString *strAreaName = kAreaName;
NSRange boldedRange = [strAreaName rangeOfString:strAreaName];

NSMutableAttributedString *newAttString = [[NSMutableAttributedString alloc] initWithString:strFirst];
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:strAreaName];
UIFont *fontText = [UIFont boldSystemFontOfSize:17.0];

NSDictionary *dictBoldText = [NSDictionary dictionaryWithObjectsAndKeys:fontText, NSFontAttributeName, nil];
[attrString setAttributes:dictBoldText range:boldedRange];

[newAttString appendAttributedString:attrString];

[lblFirst setAttributedText:newAttString];

输出:
只有在美国时,用户才能使用该应用程序功能

但是我想要OLD和Italic的美国

请指导我添加我的字符​​串。

,谢谢,
Mihir

最佳答案

也许您可以尝试以下代码:

//----Creating font dictionary for bold-italic text

UIFontDescriptor *fontDescriptor = [UIFontDescriptor preferredFontDescriptorWithTextStyle:UIFontTextStyleBody];

UIFontDescriptor *fontDescriptorNew;
NSDictionary *dictBoldItalicText;

uint32_t NewStyles = [fontDescriptor symbolicTraits] | UIFontDescriptorTraitBold | UIFontDescriptorTraitItalic;
fontDescriptorNew = [fontDescriptor fontDescriptorWithSymbolicTraits:NewStyles];
UIFont *updatedFont = [UIFont fontWithDescriptor:fontDescriptorNew size:17.0];//set your font size
dictBoldItalicText = @{ NSFontAttributeName : updatedFont };

//----------

NSString *strFirst = [NSString stringWithFormat:@"The App feature is only available to users while at "];
NSString *strAreaName=@"America";

NSRange boldedRange = [strAreaName rangeOfString:strAreaName];

NSMutableAttributedString *newAttString = [[NSMutableAttributedString alloc] initWithString:strFirst];
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:strAreaName];


[attrString setAttributes:dictBoldItalicText range:boldedRange];//Assigning bold-italic attribute dictionary

[newAttString appendAttributedString:attrString];

[lblFirst setAttributedText:newAttString];

经过测试,工作正常。

关于ios - 在Objective-c中如何在没有第三方库的情况下对我的字符串显示粗体和斜体,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38140576/

10-12 14:44