我创建了一个简单的聊天应用程序,我们的消息位于右侧(右对齐),所有其他消息位于左侧(左对齐)。我正在使用NSAttributedString
,因为我用颜色等大量修改了文本。每条消息都是一个 UILabel。我的问题是,在正确对齐的消息末尾,我想放一个空格,所以它看起来像这样:
"Some example sentence "
而不是这样:
"Some example sentece"
并且每次我将空格放在那里时它都会被删除(我也尝试过使用不间断空格\u00a0
,但我遇到了同样的问题(空格被删除)我的右对齐代码如下所示:
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self.text /*attributes:attrDict*/];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setAlignment:NSTextAlignmentRight];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [attributedString length])];
后来我添加了一些其他属性与颜色等(没有改变文本本身)。文本的末尾总是带有空格,如下所示:"Some example sentece "
最后我做了这样的事情:
self.attributedText = attributedString;
而且……我的空间被删除了。如何防止我的文本在末尾删除空格?我在那里需要它。
编辑:
if (self.textAlignment == NSTextAlignmentRight) {
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setAlignment:NSTextAlignmentRight];
[paragraphStyle setTailIndent:0.1];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [attributedString length])];
}
这是我的 tailIndent 代码,它看起来像这样。我在tailIndent之前在聊天的右侧有一条消息“测试”(这里在左侧,因为我不知道如何右对齐文本:P):
测试
在tailIndent之后:
吨
那么会发生什么:在这种情况下,文本从右到左只留下最后一个字符。而tailIndent 是唯一的0.1
!