是否存在一种方法可以在普通字符串中 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
最佳答案
我建议使用标准的NSAttributedString
和NSBaselineOffsetAttributeName
。看一下我刚刚整理的示例:
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)
}
结果如下:
关于swift - NSMutableAttributedString 用于从 String 为 NSTextView 添加下标(上标),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41006438/