UITextView我应该在哪里设置属性字符串的颜色和字体

当我在故事板中使用UITextView时,我可以选择文本作为属性字符串并设置其属性,如颜色,字体和其他属性。 当我在代码中设置textView.text = @"my string" ,它会显示为我设置的内容。

我的问题是,如果我想在代码中执行此操作,那么这与故事板属性设置相同? 从文档https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITextView_Class/index.html#//apple_ref/occ/instp/UITextView/text我看到一些属性,即textColor,字体,但缺乏某些属性,我可以像行高一样设置。

这是通过属性字符串对象完成的! 你一定要看一下编程指南: https : //developer.apple.com/library/ios/documentation/Cocoa/Conceptual/AttributedStrings/AttributedStrings.html

根据要求,提供一个简短示例,说明如何创建属性字符串。

 - (void)viewDidLoad { [super viewDidLoad]; // // Example 1: Create attributed string and set attributes for ranges // NSString *plainString = @"Hello World"; NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:plainString]; // change the font of the entire string [attributedString addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Courier New" size:16.0] range:NSMakeRange(0, plainString.length)]; // set the font color to blue for the word 'World' [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(6, 4)]; // assign to texfield 1 self.tfAttributedString1.attributedText = attributedString; // // Example 2: Create attributed string based on html // NSString *htmlString = @"

Hello html

"; NSData *htmlStringData = [htmlString dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *attributedStringOptions = @{ NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding) }; // assign to texfield 2 self.tfAttributedString2.attributedText = [[NSAttributedString alloc] initWithData:htmlStringData options: attributedStringOptions documentAttributes:nil error:nil]; }

这就是结果如下:

结果截图