ios - UITextView 我应该在哪里为属性字符串设置颜色和字体
<p><p>当我在 Storyboard中使用 UITextView 时,我可以选择文本作为属性字符串并设置其属性,如颜色、字体和其他属性。当我在代码中设置 <code>textView.text = @"my string"</code> 时,它会按照我的设置显示。</p>
<p>我的问题是,如果我想在代码中执行此操作,那么这个 Storyboard 属性设置等效于什么?来自文档 <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITextView_Class/index.html#//apple_ref/occ/instp/UITextView/text" rel="noreferrer noopener nofollow">https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITextView_Class/index.html#//apple_ref/occ/instp/UITextView/text</a>我看到了一些属性,例如 textColor、字体,但缺少一些我可以设置的属性,例如 line-height。</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>这是通过属性字符串对象完成的!你绝对应该看看编程指南:
<a href="https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/AttributedStrings/AttributedStrings.html" rel="noreferrer noopener nofollow">https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/AttributedStrings/AttributedStrings.html</a> </p>
<p>根据要求,提供一个简短示例,展示如何创建属性字符串。</p>
<pre><code>- (void)viewDidLoad
{
;
//
// Example 1: Create attributed string and set attributes for ranges
//
NSString *plainString = @"Hello World";
NSMutableAttributedString *attributedString = [ initWithString:plainString];
// change the font of the entire string
[attributedString addAttribute:NSFontAttributeName
value:
range:NSMakeRange(0, plainString.length)];
// set the font color to blue for the word 'World'
[attributedString addAttribute:NSForegroundColorAttributeName
value:
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 = ;
NSDictionary *attributedStringOptions = @{
NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)
};
// assign to texfield 2
self.tfAttributedString2.attributedText = [ initWithData:htmlStringData
options: attributedStringOptions
documentAttributes:nil error:nil];
}
</code></pre>
<p>这就是结果的样子:</p>
<p> <img src="/image/zyUtj.png" alt="Screenshot of the result"/> </p></p>
<p style="font-size: 20px;">关于ios - UITextView 我应该在哪里为属性字符串设置颜色和字体,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/28591010/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/28591010/
</a>
</p>
页:
[1]