具有右对齐的NSAttributedString在末尾删除空格

问题描述 投票:2回答:1

我创建了一个简单的聊天应用程序,其中我们的消息在右侧(右对齐),所有其他消息在左侧(左对齐)。我正在使用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之前,我在聊天的右侧有一条消息“test”(这里是左边因为我不知道如何正确对齐文本:P):

测试

在tailIndent之后:

Ť

那么会发生什么:文本从右到左,在这种情况下只留下最后一个字符。而tailIndent只是0.1

objective-c whitespace nsattributedstring nsmutableattributedstring right-align
1个回答
6
投票

我自己尝试了一些值,并且,与属性名称设置的期望(以及缺乏其他指导in the 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;

enter image description here

将行设置tailIndent取消注释为负值,您将获得:

enter image description here

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

NSNumber *theIndent = @(-18);

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

只有像NSNumbers这样的对象可以放在数组,字典,核心数据等中。

© www.soinside.com 2019 - 2024. All rights reserved.