如何在UITextView中附加文本

时间:2015-06-08 16:24:03

标签: ios swift uitextview

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

示例:

This is the UITextView with random  properties.

                         This is the watermark.

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

尝试使用属性字符串:

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;

答案 2 :(得分:0)

这里是@ 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