我正在尝试使用NSMutableAttributedString来格式化文本,使其左对齐并在同一段文本上右对齐
我已在IOS Multiple right and left align on same line审核了类似的答案,但无法使标签停止正常工作。
我自己的解决方案是执行以下操作。
让我的副本+添加物理标签(即:\t
)到副本的末尾
然后为我的聊天时间字符串创建一个段落样式,该字符串右对齐并将其附加到字符串的末尾。
我几乎让它上班;
但问题是时间根本没有对齐;它似乎被卡住了左对齐。
我希望时间文字在右侧。
以下是我设置时间部分的代码;
NSAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:message.body attributes:attributes];
NSMutableAttributedString *finalizedCopy = [attributedString mutableCopy];
if (message.sender.remoteID) [finalizedCopy appendAttributedString:tabStops];
// Add time to the chat bubble
NSString *messageTime = [[JSQMessagesTimestampFormatter sharedFormatter] timeForDate:message.date];
NSAttributedString *chatMessageTime = [[NSAttributedString alloc] initWithString:messageTime attributes:attributes];
NSMutableParagraphStyle *timeParagraphStyle = [[NSMutableParagraphStyle alloc] init];
timeParagraphStyle.alignment = NSTextAlignmentRight;
NSMutableAttributedString *dateString = [[NSMutableAttributedString alloc] initWithAttributedString:chatMessageTime];
[dateString setAttributes:@{ NSFontAttributeName : [UIFont vic_fontOfSize:10],
NSForegroundColorAttributeName: [UIColor vic_darkTextColor]
}
range:NSMakeRange(0, dateString.length)];
[dateString addAttribute:NSParagraphStyleAttributeName value:timeParagraphStyle range:NSMakeRange(0, dateString.length)];
[finalizedCopy appendAttributedString:dateString];
attributedString = [finalizedCopy copy];
我想知道如何最好地达到预期的效果。
非常感谢
另外,如果我要使用NSTabStops - 我在哪里放置它们,在我的左手弦的末尾或右手弦的开头?
即:
NSTextTab *tabStop = [[NSTextTab alloc] initWithTextAlignment:NSTextAlignmentRight location:150 options:nil];
[paragraph setTabStops:@[tabStop]];
[finalizedCopy addAttribute:NSParagraphStyleAttributeName value:paragraph range:NSMakeRange(0, finalizedCopy.length)];
在我的左手弦的末尾,但我看不到任何结果。
答案 0 :(得分:0)
这里有一些通用的Swift代码可以实现您想要的功能。同样的方法也应该在Objective-C中起作用:
// Paragraph with left and right aligned text
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .left
for tabStop in paragraph.tabStops {
paragraph.removeTabStop(tabStop)
}
paragraph.addTabStop(NSTextTab(textAlignment: .right, location: 240.0, options: [:]))
let text = NSMutableAttributedString()
let leftAttributes = [
NSFontAttributeName: UIFont.systemFont(ofSize: 10.0),
NSForegroundColorAttributeName: UIColor.white,
NSParagraphStyleAttributeName: paragraph
]
let rightAttributes = [
NSFontAttributeName: UIFont.boldSystemFont(ofSize: 20.0),
NSForegroundColorAttributeName: UIColor.white,
NSParagraphStyleAttributeName: paragraph
]
let data = [
"Carrots": 23,
"Pears": 453,
"Apples ": 2350
]
for (key, value) in data {
text.append(NSAttributedString(string: key, attributes: leftAttributes))
text.append(NSAttributedString(string: "\t\(value)\n", attributes: rightAttributes))
}