如何更改NSTextView中选定文本的大小?

时间:2019-06-25 17:18:05

标签: objective-c

我有一个NSTextView,我正在尝试创建一个简单的文本编辑器。我的文本视图可以具有几种不同的字体。例如,如果从文本视图中选择的文本具有两种不同的字体,我如何仅更改选择的文本的大小?

1 个答案:

答案 0 :(得分:0)

在textView中的文本被选中时,您可以使用textViewDidChangeSelection: UITextViewDelegate回调,并根据所选范围更改其属性。这是将所选文本更改为systemFont 25pt greenColor的示例:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.defaultAttributes = @{NSFontAttributeName: [UIFont systemFontOfSize:17.0f], NSForegroundColorAttributeName : [UIColor blackColor]};
}

- (void)textViewDidChangeSelection:(UITextView *)textView {
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        // set the entire text view to the default attributes initially (in case previously selected text had it's attributes changed)
        [[textView textStorage] setAttributes:self.defaultAttributes range:NSMakeRange(0, textView.attributedText.length)];
        // now set our selected text to the desired attributes
        NSDictionary <NSAttributedStringKey, id> *selectedAttributes = @{NSFontAttributeName : [UIFont systemFontOfSize:25.0f], NSForegroundColorAttributeName: [UIColor greenColor]};
        [[textView textStorage] setAttributes:selectedAttributes range:textView.selectedRange];
    }];
}

您显然需要使此视图控制器成为textView的委托

https://developer.apple.com/documentation/uikit/uitextviewdelegate/1618620-textviewdidchangeselection?language=objc