简体   繁体   English

更改NSAtributedString颜色和字体为空范围TextView

[英]Change NSAtributedString Color and Font for Empty Range TextView

I recently started investigating how NSAtributedString works. 我最近开始研究NSAtributedString的工作方式。 I am building something similar to rich text editor using NSAtributedString. 我正在使用NSAtributedString构建类似于RTF编辑器的东西。 I have a custom written CustomRichTextEditor:UITextView and I want to overwrite default attributes for NSAtributedString using this code below: 我有一个自定义的CustomRichTextEditor:UITextView,我想使用下面的代码覆盖NSAtributedString的默认属性:

UIFont *font = [UIFont systemFontOfSize:24.0];
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName,[UIColor darkGrayColor],NSForegroundColorAttributeName,nil];
NSMutableAttributedString* attrStr = [self.richTextEditor.attributedText mutableCopy];
[attrStr setAttributes:attributes
                 range:NSMakeRange(0, self.richTextEditor.attributedText.string.length-1)

 ];
self.richTextEditor.attributedText = attrStr;

However, because my editor is empty and range is unknown, I crash with error: 但是,由于我的编辑器为空并且范围未知,因此我崩溃并报错:

Terminating app due to uncaught exception 'NSRangeException', reason: 'NSMutableRLEArray replaceObjectsInRange:withObject:length:: Out of bounds' 由于未捕获的异常“ NSRangeException”而终止应用程序,原因:“ NSMutableRLEArray replaceObjectsInRange:withObject:length ::越界”

How can I set the font and color for NSAtributedString correctly when the range is unknown? 当范围未知时,如何正确设置NSAtributedString的字体和颜色?

Well, you set the ranges length like this: 好吧,您可以这样设置范围长度:

self.richTextEditor.attributedText.string.length-1

which can make errors. 可能会出错。 If you make 0 - 1 to an unsigned integer it will suddenly becomes pretty big and therefore your range will be super huge. 如果您将0-1设为一个无符号整数,则它将突然变得非常大,因此您的范围将非常巨大。

So what you need to do is check if you have a string.length > 0 before you make your range. 因此,您需要做的是在确定范围之前检查string.length > 0 Executing all the code is anyway useless if your string is empty... 如果您的字符串为空,执行所有代码将毫无用处...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM