How to add text to a UITextView

I have UITextViewwith random properties and random size. I need to add the watermark recorded in UITextView. But the watermark should have different text properties and different alignment.

Example:

This is the UITextView with random  properties.

                         This is the watermark.
+4
source share
3 answers

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

UITextViewhas property textand property attributedText. In your case, use the property attributedTextafter creating the assigned string.

0
source

Try using an 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;
0
source

Here's the translation of @skorolkov 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
0
source

All Articles