我有一个NSTextView,我正在尝试创建一个简单的文本编辑器。我的文本视图可以具有几种不同的字体。例如,如果从文本视图中选择的文本具有两种不同的字体,我如何仅更改选择的文本的大小?
答案 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的委托