简体   繁体   English

如何在 SwiftUI 中使用 Core Text

[英]How to use Core Text in SwiftUI

I have a basic implementation of Core Text that prints Hello World in iOS, it works perfectly with UIKit.我有一个基本的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)
    }
}

I've tried to use this Core Text with SwiftUI instead of UIKit by applying the use of UIViewRepresentable :我试着通过应用使用使用这个核心文本与SwiftUI代替UIKit的UIViewRepresentable

import SwiftUI
import CoreText

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

But I couldn't figure out how to implement (or basically, override) the draw function, since we use structs instead of classes in SwiftUI.但是我无法弄清楚如何实现(或基本上覆盖)绘制函数,因为我们在 SwiftUI 中使用结构而不是类。

In addition to that, how can we do the same thing for macOS?除此之外,我们如何为 macOS 做同样的事情?

Just wrap your previous CTView , as in只需包装您以前的CTView ,如

struct WrappedCTView: UIViewRepresentable {

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM