L3M*_*M0L 2 whitespace objective-c nsattributedstring right-align nsmutableattributedstring
我创建了一个简单的聊天应用程序,其中我们的消息在右侧(右对齐),所有其他消息在左侧(左对齐).我正在使用,NSAttributedString因为我大量修改文本的颜色等.每条消息都是UILabel.我的问题是,在正确对齐的消息的末尾,我想放一个空格,所以它看起来像这样:
"Some example sentence "
Run Code Online (Sandbox Code Playgroud)
而不是这样的:
"Some example sentece"
Run Code Online (Sandbox Code Playgroud)
每次我把空白放在那里它都被删除了(我也尝试了不间断的空间\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])];
Run Code Online (Sandbox Code Playgroud)
后来我添加了一些其他属性与颜色等(没有任何改变文本本身).文本总是像最后一样用最后的空格:"Some example sentece "
最后我做这样的事情:
self.attributedText = attributedString;
Run Code Online (Sandbox Code Playgroud)
并且...我的空间被删除了.如何防止我的文本删除最后的空格?我需要那里.
编辑:
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])];
}
Run Code Online (Sandbox Code Playgroud)
这是我的tailIndent代码,它看起来像这样.在tailIndent之前,我在聊天的右侧有一条消息"test"(这里是左边因为我不知道如何正确对齐文本:P):
测试
在tailIndent之后:
Ť
那么会发生什么:文本从右到左,在这种情况下只留下最后一个字符.只有tailIndent 0.1!
我自己尝试了一些值,并且,与属性名称设置的期望(以及文档中缺少其他指导)相反,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;
Run Code Online (Sandbox Code Playgroud)
将行设置取消注释tailIndent为负值,您将获得:
编辑 任何控制参数应表示为对象,如表示缩进的NSNumber:
NSNumber *theIndent = @(-18);
// then, later:
paragraphStyle.tailIndent = [theIndent intValue];
Run Code Online (Sandbox Code Playgroud)
只有像NSNumbers这样的对象可以放在数组,字典,核心数据等中.
| 归档时间: |
|
| 查看次数: |
1767 次 |
| 最近记录: |