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

标签 ios uitextview nsattributedstring

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

我的问题是,如果我想在代码中执行此操作,那么与此 Storyboard 属性设置等效的是什么?来自文档 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 = @"<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];
}

结果是这样的:

Screenshot of the result

关于ios - UITextView 我应该在哪里设置属性字符串的颜色和字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28591010/

相关文章:

iphone - 为几个ios版本导入 header ?

ios - 数组 Swift 中的求和级数

iphone - 从 UITextView 中删除底部空间

objective-c - UITextView textviewshouldendediting 从未调用过

cocoa - 如何使用 NSAttributedString 创建下标

ios - NSAttributedString 如何遵循 MVC 范式?

android - Xamarin 是摄像头监控应用程序的完美工具吗?

ios - 执行 Push Segue 时是否应该释放 UIViewController

ios - 如何通过 Swift 检查键盘输入的特殊字符 "#",如标签

objective-c - 如何在 NSTextView 中绘制特定范围文本的背景