objective-c - 如何从 NSTextView 更改所选文本的大小?
问题描述
我有一个 NSTextView,我正在尝试创建一个简单的文本编辑器。我的文本视图可以有几种不同的字体。例如,如果从 textview 中选择的文本有两种不同的字体,我怎样才能改变所选文本的大小?
解决方案
您可以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 的委托
推荐阅读
- xcode - 多个命令产生 Parse.bundle
- javascript - 使用 browserify + babel 的 gulp.task 语法问题
- typescript - 如何使用 Mocha Chai 单元测试来测试一个函数是否有两个字符串参数
- javascript - 如何摆脱 React.js 中的 NO ACCESS CONTROL ORIGIN 错误?
- html - 带字幕的 HTML 文本
- drake - 输入端口的索引是什么意思?
- kubernetes - 在 k8s 集群上运行的 ansible 的正确 dockerfile
- c# - 搜索字典值的字符串,然后用字典的键替换匹配的值?
- c++ - 计算树中大于输入名称的名称数量的函数
- authentication - 我正在尝试通过在应用程序之间共享 cookie(登录和网页)在 .net core 3.1 中实现 SSO