簡體   English   中英

如何在UITextView中附加文本

[英]How to append text in UITextView

我有一個隨機屬性和隨機大小的UITextView 我需要在UITextView附加一個水印。 但水印需要具有不同的文本屬性和不同的對齊方式。

例:

This is the UITextView with random  properties.

                         This is the watermark.

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

UITextView具有text屬性和attributedText屬性。 在您的情況下,在創建屬性字符串后使用attributedText屬性。

嘗試使用屬性字符串:

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;

這是@ 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM