我创建了一个简单的聊天应用程序,其中我们的消息位于右侧(右对齐),所有其他消息位于左侧(左对齐)。我正在使用 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 代码,它的作用如下所示。 我在聊天的右侧有一条消息“测试”(这里是左侧,因为我不知道如何右对齐文本:P) 在 tailIndent 之前:
test
tailIndent 之后:
t
那么会发生什么:在这种情况下,文本从右到左只留下最后一个字符。而且 tailIndent 仅为 0.1
!
最佳答案
我自己尝试了一些值,并且与属性名称设置的预期相反(并且缺乏其他指导 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;
取消注释行设置 tailIndent
为一个负值,你会得到:
编辑 任何控制参数都应表示为对象,例如表示缩进的 NSNumber:
NSNumber *theIndent = @(-18);
// then, later:
paragraphStyle.tailIndent = [theIndent intValue];
只有对象,比如NSNumbers,可以放在数组、字典、核心数据等中。
关于objective-c - 右对齐的 NSAttributedString 删除末尾的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39317628/