首页 > 解决方案 > 如何从 NSTextView 更改所选文本的大小?

问题描述

我有一个 NSTextView,我正在尝试创建一个简单的文本编辑器。我的文本视图可以有几种不同的字体。例如,如果从 textview 中选择的文本有两种不同的字体,我怎样才能改变所选文本的大小?

标签: objective-c

解决方案


您可以textViewDidChangeSelection:在选择 textView 中的文本时使用 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


推荐阅读