如何在我的UITextView使用NSMutableAttributedString加粗一些单词?

我有一个UITextView,并且有一些我正在使用NSString stringWithFormat进行投射,我想用粗体显示。

我已经看过周围堆栈溢出,并试图按照post,但我想我不理解它。

这是我一直在玩的东西:

NSRange boldedRange = NSMakeRange(0, 4); NSString *boldFontName = [[UIFont fontWithName:@"Helvetica-Bold" size:100]fontName]; NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:self.name]; [attrString beginEditing]; [attrString addAttribute:NSFontAttributeName value:boldFontName range:boldedRange]; [attrString endEditing]; self.resultsTextView.attributedText = attrString; self.resultsTextView.text = [NSString stringWithFormat:@"One day, %@ was taking a walk and saw a %@ boy. He was %@ a %@.", attrString, self.adjective, self.adverb, self.noun]; 

如果您想通过将字典作为整体设置为属性,也可以按照以下方式进行设置

 NSString *strTextView = @"This is some demo Text to set BOLD"; NSRange rangeBold = [strTextView rangeOfString:@"BOLD"]; UIFont *fontText = [UIFont boldSystemFontOfSize:10]; NSDictionary *dictBoldText = [NSDictionary dictionaryWithObjectsAndKeys:fontText, NSFontAttributeName, nil]; NSMutableAttributedString *mutAttrTextViewString = [[NSMutableAttributedString alloc] initWithString:strTextView]; [mutAttrTextViewString setAttributes:dictBoldText range:rangeBold]; [textViewTermsPolicy setAttributedText:mutAttrTextViewString]; 

使用下面的代码在TextView中设置属性string。

  NSString *infoString =@"I am Kirit Modi from Deesa."; NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:infoString]; UIFont *font_regular=[UIFont fontWithName:@"Helvetica" size:20.0f]; UIFont *font_bold=[UIFont fontWithName:@"Helvetica-Bold" size:20.0f]; [attString addAttribute:NSFontAttributeName value:font_regular range:NSMakeRange(0, 4)]; [attString addAttribute:NSFontAttributeName value:font_bold range:NSMakeRange(5, 15)]; [attString addAttribute:NSFontAttributeName value:font_regular range:NSMakeRange(16, infoString.length - 15 - 1)]; [self.txtView setAttributedText:attString]; 

输出:

在这里输入图像说明

在@Bbrame和@BenoitJadinon上检查@CrazyYoghurt在这个以前的SO问题上的改进3586871我已经使用它一年多了,它工作的很好。 一个限制:如果在原始string中出现多次,我不认为可以多次加粗同一个string。 但是如果你愿意的话,你也许可以花费代码来完成它。