How to append text in UITextView

4.1k views Asked by At

I have a UITextView with random properties and random size. I need to append a watermark written into a UITextView. But the watermark needs to have different text properties and different alignment .

Example:

This is the UITextView with random  properties.

                         This is the watermark.
3

There are 3 answers

0
AudioBubble On

You need to use attributed strings (NSAttributedString) instead of strings (NSString).

UITextView has a text property and an attributedText property. In your case, use the attributedText property once you have created the attributed string.

0
skorolkov On

Try using attributed string:

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;
1
Marcus Rossel On

Here's a translation of @skorolkov's Objective-C code:

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