如何允许NSAttributedString文本输入UITextView?

时间:2013-05-07 16:04:21

标签: ios uitextview nsattributedstring

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

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

我已经使用-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text UITextView委托方法获取text参数,并通过创建具有相同文本的NSAttributedString来使用属性对其进行修改。然后创建一个NSMutableAttributedString,它是textView的attributionText的副本。使用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;                
}

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

attributedText issues

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

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

3 个答案:

答案 0 :(得分:32)

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

答案 1 :(得分:4)

如果您正在寻找示例

,以下是示例代码

Swift 3.0

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

<强>目标C

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

答案 2 :(得分:0)

这个代码可以用,我猜它可能有帮助

NSMutableAttributedString *string=[[NSMutableAttributedString alloc] initWithString:@"NEW ? String"];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, 3)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(3,5)];
self.text.attributedText=string;
self.textViewss.attributedText=string;