如何在 SwiftUI 中使用 Core Text

How to use Core Text in SwiftUI

我有一个 Core Text 的基本实现,它在 iOS 中打印 Hello World,它与 UIKit 完美配合。

import UIKit
import CoreText

class CTView: UIView {
    override func draw(_ rect: CGRect) {
        guard let context = UIGraphicsGetCurrentContext() else { return }
        
        // Flip the coordinate system
        context.textMatrix = .identity
        context.translateBy(x: 0, y: bounds.size.height)
        context.scaleBy(x: 1.0, y: -1.0)
        
        let path = CGMutablePath()
        path.addRect(bounds)
        
        let attrString = NSAttributedString(string: "Hello World")
        
        let framesetter = CTFramesetterCreateWithAttributedString(attrString as CFAttributedString)
        
        let frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, attrString.length), path, nil)
        
        CTFrameDraw(frame, context)
    }
}

我尝试通过使用 UIViewRepresentable:

来将此 Core Text 与 SwiftUI 而不是 UIKit 一起使用
import SwiftUI
import CoreText

struct CTView: UIViewRepresentable {
    func makeUIView(context: Context) -> UIView {
        return UIView()
    }
    
    func updateUIView(_ uiView: UIView, context: Context) {
        
    }
}

但我无法弄清楚如何实现(或基本上覆盖)绘制函数,因为我们在 SwiftUI 中使用结构而不是 类。

除此之外,我们如何为 macOS 做同样的事情?

只需包装您之前的 CTView,如

struct WrappedCTView: UIViewRepresentable {

    func makeUIView(context: Context) -> CTView {
        let view = CTView()       // << here !!
        view.isOpaque = false
        return view
    }
    
    func updateUIView(_ uiView: CTView, context: Context) {}
}