繁体   English   中英

如何允许NSAttributedString文本输入UITextView?

[英]How to allow NSAttributedString text be typed into a UITextView?

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

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

我使用了-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text UITextView委托方法获取text参数,并通过创建具有相同属性的NSAttributedString来修改它文本。 然后创建一个NSMutableAttributedString,它是textView的attributedText的副本。 使用appendAttributedString附加两个,然后将appendAttributedStringattributedText属性设置为生成的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;                
}

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

attributionText问题

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

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

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

如果您正在寻找示例,以下是示例代码

Swift 3.0

var attributes = textField.typingAttributes
attributes["\(NSForegroundColorAttributeName)"] = UIColor.red
textField.typingAttributes = attributes

Objective-C的

NSMutableDictionary* attributes = [textField.typingAttributes mutableCopy];
attributes[NSForegroundColorAttributeName] = [UIColor redColor];
textField.typingAttributes = attributes;

暂无
暂无

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

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