如何在ios中的textView中显示不同字体的文本?

嗨,我正在做一个应用程序。 在那我需要以不同的字体显示文字。 我的意思是如果我用一种字体显示名字,并用不同的字体显示城市名称。

UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(50, 50, 200, 100)]; textView.text = @"Vijay Apple Dev"; NSString *textViewText = textView.text; NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:textViewText]; [attributedText addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Courier" size:20] range:[textViewText rangeOfString:@"Apple"]]; [attributedText addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Verdana" size:20] range:[textViewText rangeOfString:@"Vijay"]]; textView.attributedText = attributedText; [self.view addSubview:textView]; 

在这里输入图像说明

尝试像这样做…并根据您的要求,如字体名称和字体大小进行自定义

  NSString *firstName = @"FirstName"; NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:firstName]; UIFont *font = [UIFont fontWithName:@"Helvetica" size:20]; [attributedString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, firstName.length)];// Here define your range. textView.attributedText = attributedString; 
 //Use attributed String //Apply properties to both strings //then merge and set it to textview NSString *selectedString=@"Hey,"; UIFont *fontSelectedText = [UIFont boldSystemFontOfSize:25]; NSDictionary *dictBoldSelectedText = [NSDictionary dictionaryWithObjectsAndKeys:fontSelectedText, NSFontAttributeName, nil]; NSMutableAttributedString *mutAttrTextViewSelectedString = [[NSMutableAttributedString alloc] initWithString:selectedString]; [mutAttrTextViewSelectedString setAttributes:dictBoldSelectedText range:NSMakeRange(0,selectedString.length)]; [_tTextView setAttributedText:mutAttrTextViewSelectedString]; //Second String NSString *restOfStrig=@"\nHello"; NSMutableAttributedString *mutAttrTextViewString = [[NSMutableAttributedString alloc] initWithString:restOfStrig]; UIFont *fontText = [UIFont boldSystemFontOfSize:16]; NSDictionary *dictBoldText = [NSDictionary dictionaryWithObjectsAndKeys:fontText, NSFontAttributeName, nil]; [mutAttrTextViewString setAttributes:dictBoldText range:NSMakeRange(0,restOfStrig.length)]; //Combining both the Attributed String [mutAttrTextViewSelectedString appendAttributedString:mutAttrTextViewString]; NSMutableAttributedString * finalAttributedStr=[[NSMutableAttributedString alloc] initWithAttributedString:mutAttrTextViewSelectedString]; //setting it to the textView [_tTextView setAttributedText:finalAttributedStr]; 

使用NSAttributedString

NSAttributedString对象pipe理适用于string中单个字符或字符范围的string和相关属性集(例如字体和字距)。 字符及其属性的关联称为属性string。 集群的两个公共类NSAttributedString和NSMutableAttributedString分别为只读属性string和可修改的属性string声明编程接口。

NSAttributedString

当你创build你的属性string,然后将其设置为你的textView: self.textView.attributedText = myAttributedString;