删除线未显示,但下划线显示。代码如下,非常简单。当我注释掉下划线时,文本显示没有删除线,当我注释掉删除线并显示下划线时它工作正常。我已经尝试了一切 - 我必须遗漏一些明显的东西,文档说三振出去应该有效。
我正在运行macOS 10.13.6和Xcode 10.1。
import AppKit
import PlaygroundSupport
class CustomView: NSView {
override func draw(_ dirtyRect: NSRect) {
let attrString = NSAttributedString(
string: "Hello",
attributes: [
//NSAttributedString.Key.underlineStyle: NSUnderlineStyle.thick.rawValue,
NSAttributedString.Key.strikethroughStyle: NSUnderlineStyle.thick.rawValue
]
)
let line = CTLineCreateWithAttributedString(attrString)
// Set text position and draw the line into the graphics context.
let context = (NSGraphicsContext.current?.cgContext)!
context.translateBy(x: 10, y: 10)
CTLineDraw(line, context)
}
}
let customView = CustomView(frame: NSRect(x: 0, y: 0, width: 400, height: 400))
PlaygroundPage.current.liveView = customView
游乐场设置。要在Xcode Playground中运行此功能,请确保在检查器设置中将平台更改为macOS(默认情况下,所有新操场都设置为iOS)。
CoreText没有对删除线印刷文本修饰的本机支持(但支持下划线就像你在问题中提到的那样很好)。 CoreText支持的完整字符串属性列表是described here。
这个古老的Objective-C based blog post提供了使用CoreText API手动实现删除线的必要细节。不幸的是,根本不是快速修复。
较高级别的TextKit框架确实提供了删除支持。要快速查看工作,只需在原始代码中替换此行:
CTLineDraw(line, context)
改为:
attrString.draw(at: .zero)
顺便说一句,这有助于验证你的原始NSAttributedString
开始没有任何问题;)
当然,根据您的代码依赖CoreText的程度,切换到TextKit可能是一项非常重要的任务,因此您还需要牢记这一点。