【问题标题】:How to append text in UITextView如何在 UITextView 中添加文本
【发布时间】:2026-02-15 15:10:01
【问题描述】:

我有一个UITextView,具有随机属性和随机大小。我需要附加写入UITextView 的水印。但是水印需要有不同的文字属性和不同的对齐方式。

例子:

This is the UITextView with random  properties.

                         This is the watermark.

【问题讨论】:

  • 如果您想要一个具有多个文本属性的UITextView,您需要将UITextViewattributedText 属性设置为NSAttributedString
  • Stack Overflow 是一个问答网站。您发布的是一系列毫无疑问的陈述。

标签: ios swift uitextview


【解决方案1】:

您需要使用属性字符串 (NSAttributedString) 而不是字符串 (NSString)。

UITextView 有一个 text 属性和一个 attributedText 属性。在您的情况下,请在创建属性字符串后使用 attributedText 属性。

【讨论】:

    【解决方案2】:

    尝试使用属性字符串:

    NSString *textViewText = @"...";
    NSString *watermarkText = @"\nThis is the watermark";
    NSString *fullText = [textViewText stringByAppendingString:watermarkText];
    
    NSMutableParagraphStyle *watermarkParagraphStyle = [NSMutableParagraphStyle new];
    watermarkParagraphStyle.alignment = NSTextAlignmentCenter;
    
    NSMutableAttributedString *fullTextAttributed = [[NSMutableAttributedString alloc] initWithString:fullText];
    [fullTextAttributed addAttribute:NSParagraphStyleAttributeName
                               value:watermarkParagraphStyle
                               range:[fullText rangeOfString:watermarkText]];
    textView.attributedText = fullTextAttributed;
    

    【讨论】:

      【解决方案3】:

      这是@skorolkov 的 Objective-C 代码的翻译:

      let textViewText = "..."
      let watermarkText = "\nThis is the watermark"
      let fullText = textViewText + watermarkText
      
      let watermarkParagraphStyle = NSMutableParagraphStyle()
      watermarkParagraphStyle.alignment = NSCenterTextAlignment
      
      let fullTextAttributed = NSMutableAttributedString(string: fullText)
      fullTextAttributed.addAttribute(NSParagraphStyleAttributeName,
                               value: watermarkParagraphStyle,
                               range: fullText.rangeOfString(waterMarkText))
      textView.attributedText = fullTextAttributed
      

      【讨论】:

      • 在第 8 行出现错误:无法将表达式的类型 '(NSString!, value: NSMutableParagraphStyle, range: Range?)' 转换为类型 '(String, value: AnyObject,范围:NSRange) -> Void'