如何允许NSAttributedString文本输入UITextView?

Joe*_*Joe 11 uitextview nsattributedstring ios

我正在尝试允许将不同样式的文本输入到UITextView中,有点像文本编辑器,使用粗体或斜体等简单属性.我理解通过使用textView的attributedText属性,我可以将属性应用于特定范围的文本.这很好,但我希望能够将属性文本键入textView,它将通过按钮切换(例如输入粗体文本).

这是我到目前为止所想到的:

我已经使用-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)textUITextView委托方法获取text参数,并通过创建具有相同文本的NSAttributedString来使用属性对其进行修改.然后创建一个NSMutableAttributedString,它是originText的副本textView.使用appendAttributedString,添加两个,然后将textView的attributedText属性设置为生成的attributionString.

这是代码:

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {

   if (self.boldPressed) {

        UIFont *boldFont = [UIFont boldSystemFontOfSize:self.textView.font.pointSize];
        NSDictionary *boldAttr = [NSDictionary dictionaryWithObject:boldFont forKey:NSFontAttributeName];
        NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc]initWithString:text attributes:boldAttr];
        NSMutableAttributedString *textViewText = [[NSMutableAttributedString alloc]initWithAttributedString:textView.attributedText];
        [textViewText appendAttributedString:attributedText];
        textView.attributedText = textViewText;

           return NO;
       }
   return YES;                
}
Run Code Online (Sandbox Code Playgroud)

每次输入一个字符时都必须重置textViews attributionText似乎对于一个简单的操作有点多.不仅如此,它还不能正常工作.以下是启用粗体属性时的样子:

attributionText问题

这有两个问题.最明显的是每个新角色如何被置于一条新线上.但同样奇怪的是插入点始终位于textview中文本的第一个索引处(仅当启用粗体时,粗体字符才会插入新行).因此,如果您使用粗体启用键入,然后关闭加粗,请在所有现有文本前键入简历.

我不确定为什么会发生这些错误.我也不认为我的解决方案非常有效,但我想不出任何其他实现方法.

Rob*_*ier 35

setTypingAttributes:是为了什么.只要用户按下您的某个属性按钮,新的字符就会获取所请求的属性,请将其设置为属性字典.


Fan*_*ing 6

如果您正在寻找示例,这里是示例代码

斯威夫特 3.0

var attributes = textField.typingAttributes
attributes["\(NSForegroundColorAttributeName)"] = UIColor.red
textField.typingAttributes = attributes
Run Code Online (Sandbox Code Playgroud)

目标-C

NSMutableDictionary* attributes = [textField.typingAttributes mutableCopy];
attributes[NSForegroundColorAttributeName] = [UIColor redColor];
textField.typingAttributes = attributes;
Run Code Online (Sandbox Code Playgroud)