objective-c - 右对齐的 NSAttributedString 删除末尾的空格

标签 objective-c whitespace nsattributedstring nsmutableattributedstring right-align

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

enter image description here

取消注释行设置 tailIndent 为一个值,你会得到:

enter image description here

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

NSNumber *theIndent = @(-18);

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

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

关于objective-c - 右对齐的 NSAttributedString 删除末尾的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39317628/

相关文章:

ios - Objective-C 中的 `isNan`

ios - 将 touchupinside 添加到以编程方式创建的按钮,并将 NSDate 提交到文本字段

emacs - 关闭 Emacs Whitespace-mode "Long Line"可视化

ios - 给 UITextView 一个可点击的 URL 链接

swift - 带有 2 个链接的 UITextView 属性文本,每个链接都有不同的颜色不起作用

ios - 表格 View 中的下拉列表

python - 无法从使用 BeautifulSoup 传递 URL 的结果中删除前导空格

jsf - 在 h :selectOneRadio 的两个单选按钮之间添加空格

ios - 在 swift attributedString 中设置字体正在删除粗体强调

objective-c - cocoa 回调设计 : Best Practice