11

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

到目前为止,这是我的想法:

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

这是代码:

-(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 属性文本,这对于一个简单的操作来说似乎有点多。不仅如此,它还不能正常工作。这是启用粗体属性时的样子:

归因文本问题

这有两个问题。最明显的是如何将每个新角色放到新行中。但同样奇怪的是,插入点始终位于 textview 中文本的第一个索引处(仅当启用粗体时,但粗体字符插入新行)。因此,如果您在启用粗体的情况下键入,然后关闭粗体,则在所有现有文本的前面键入简历。

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

4

2 回答 2

39

这是setTypingAttributes:为了什么。每当用户按下您的属性按钮之一时,将其设置为您的属性字典,新字符将获取请求的属性。

于 2013-05-07T19:25:16.373 回答
7

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

斯威夫特 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;
于 2017-05-09T03:27:05.800 回答