swift - NSMutableAttributedString 用于从 String 为 NSTextView 添加下标(上标)

标签 swift string append nstextview nsmutableattributedstring

是否存在一种方法可以在普通字符串中 append NSMutableAttributedString?

我想向 NSTextView 添加文本。这个特定的文本(字符串)引用了 Double() 变量,我想添加一些上部和底部索引(下标和上标)。

它是面向结构工程师的数学软件,输出是多行的大文本,我想知道是否存在更简单或直接的方法如何添加此索引(A = 5 m2(平方米))。

我不能强制使用数字下标字体字符(⁰ 1 2 3 ⁴ ⁵ ⁶ ⁷ ⁸ ⁹ ₀ ₁ 2 ₃ ₄ ₅ ₆ ₇ ₈ ₉),因为在某些情况下需要有偶数字母或符号子/上标。

我想知道是否存在如何创建此类属性字符串并将其添加到文本容器中的方法。

PS:我已经检查了这些答案( Swift 3.0 convert Double() to NSMutableAttributedString ),但在带有引用的 String 中使用它时遇到了麻烦,如下例所示:

var x = Double()
var y = Double()
var z = Double()
x = 10
y = 5

z = x * y  // = 50
var str = String()
str = "Random text for example porpoises:\n\nHere comes calculation part\n\nA1 = \(z) m2"

print(str)
//Random text for example porpoises:
//
//Here comes calculation part
//
//A1 = 50 m2

//"1" in "A1" should be subscripted (A_1)
//"2" in "m2" should be superscripted (m^2)

我想知道如何添加这些下标和上标并将此属性字符串放入 NSTextView

最佳答案

我建议使用标准的NSAttributedStringNSBaselineOffsetAttributeName。看一下我刚刚整理的示例:

override func viewDidLoad() {
    super.viewDidLoad()

    let label = NSTextView(frame: CGRect(x: 20, y: 20, width: 100, height: 30))
    let str = "A1 = 50 m2"

    let aString = NSMutableAttributedString(string: str)

    let myFont = NSFont(name: label.font!.fontName, size: 10.0)
    let subscriptAttributes: [String : Any] = [ NSBaselineOffsetAttributeName: -5, NSFontAttributeName:  myFont! ]
    let superscriptAttributes: [String : Any] = [ NSBaselineOffsetAttributeName: 5, NSFontAttributeName:  myFont! ]

    aString.addAttributes(subscriptAttributes, range: NSRange(location: 1, length: 1))
    aString.addAttributes(superscriptAttributes, range: NSRange(location: 9, length: 1))

    // Kerning adds a little spacing between all the characters.
    aString.addAttribute(NSKernAttributeName, value: 1.5, range: NSRange(location: 0, length: 2))
    aString.addAttribute(NSKernAttributeName, value: 1.5, range: NSRange(location: 8, length: 2))


    label.textStorage?.append(aString)

    view.addSubview(label)
}

结果如下:

enter image description here

关于swift - NSMutableAttributedString 用于从 String 为 NSTextView 添加下标(上标),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41006438/

相关文章:

python - Python 中的追加添加了额外的意外元素以在计算值之间列出

javascript - 如何使用 Javascript 数据从 jsp servlet 数据追加

ios - 应用程序启动没有返回有效的 pid 也没有启动错误

swift - UIWebView - PDF 阴影和页码

c++ - 从字符串到字符串流再到 vector<int>

c - 从文件中反转字符串,将字符串中的字符替换为另一个字符串并打印

MySQL Regex 如果字符串在 5 位数字后包含连字符

swift - 在 Swift 中是否有一种优雅的方法来确定两个日期是否相隔一年中的一周?

ios - swift tableviewcell 按钮图像问题

java - append 到 ObjectOutputStream