2

我创建了一个简单的聊天应用程序,我们的消息位于右侧(右对齐),所有其他消息位于左侧(左对齐)。我正在使用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

4

1 回答 1

7

我自己尝试了一些值,并且与属性名称所设定的期望相反(以及doc中缺乏其他指导),tailIndent必须是负面的。

这是没有属性集的代码(基本上是OP):

NSString *text = @"Am I indented?";

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setAlignment:NSTextAlignmentRight];
// paragraphStyle.tailIndent = -18.0;
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [attributedString length])];
self.label.attributedText = attributedString;

在此处输入图像描述

将行设置取消注释tailIndent负值,您会得到:

在此处输入图像描述

编辑 任何控制参数都应表示为对象,例如表示缩进的 NSNumber:

NSNumber *theIndent = @(-18);

// then, later:
paragraphStyle.tailIndent = [theIndent intValue];

只有对象,如 NSNumbers,可以放置在数组、字典、核心数据等中。

于 2016-09-07T12:06:30.967 回答