问题
When I use UITextView in storyboard, I can select text as attributed string and set its attributes like color, font and other attributes. And when I set textView.text = @"my string"
in code it show up as I set.
My question is if I want to do this in code, what would be equivalent to this storyboard attributes setting? From document https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITextView_Class/index.html#//apple_ref/occ/instp/UITextView/text I see some property i.e. textColor, font, but lack of some property that I can set like line-height.
回答1:
This is done via the attributed strings object! You should definitely have a look at the programming guide: https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/AttributedStrings/AttributedStrings.html
Upon request, a short example to show how you create an attributed string.
- (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 = @"<p style='font-family:Courier New'>Hello <span style='color:blue'>html</span></p>";
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];
}
And this is what the result will look like:

来源:https://stackoverflow.com/questions/28591010/uitextview-where-should-i-set-color-and-font-for-for-attributed-string