首页 > 解决方案 > 在 NSAttributedString 中对齐子字符串

问题描述

我正在将属性字符串写入 UITextView。它有一个左对齐的文本子字符串,后跟一个行号。我希望该行号右对齐。

我尝试将 NSParagraphStyle 应用于引用字符串,然后将引用字符串附加到文本字符串。

let alignStyle = NSMutableParagraphStyle()
alignStyle.alignment = .right
let citationAttributes: Dictionary<NSAttributedString.Key, Any> = [
   .paragraphStyle: alignStyle]
let citationString = NSAttributedString(string: citation, attributes: citationAttributes)
textLine.append(citationString)

我希望看到引文整齐地对齐到右边距,与文本在同一行。但相反,它立即出现在文本字符串的末尾。有没有办法用属性字符串实现我想要的格式化结果?

标签: nsattributedstring

解决方案


在另一个论坛上,我展示了如何使用其段落样式将选项卡添加到属性字符串。这解决了我所有的问题。

let newLine = NSMutableAttributedString(string: citation + "\t", attributes: citationAttributes)
newLine.append(NSAttributedString(string: line.text + "\n", attributes: textAttributes))
let style = NSMutableParagraphStyle()
style.lineSpacing = lineSpacingValue
let tabStop = tabStopValue
style.tabStops = [NSTextTab(textAlignment: .left, location: tabStop * 1.1, options: [:])]
newLine.addAttribute(.paragraphStyle, value: style, range: NSRange(location: 0, length: newLine.length))

推荐阅读