swift UIViewRepresentable中的图像分析交互无法正常工作

b1payxdu  于 2022-12-10  发布在  Swift
关注(0)|答案(1)|浏览(147)

我有一个简单的UIViewRepresentable Package 器,用于实时文本功能(ImageAnalysisInteraction)。它工作起来没有问题,直到我开始更新updateUIView(...)函数中的UIImage
我一直在控制台中看到此错误,它源于此视图:[api] -[CIImage initWithCVPixelBuffer:options:] failed because the buffer is nil.
当我更改图像时,它会正确更新,但selectableItemsHighlighted覆盖层保持不变,我仍然可以选择旧图像的文本(即使它不再可见)。

import UIKit
import SwiftUI
import VisionKit

@MainActor
struct LiveTextInteraction: UIViewRepresentable {
    @Binding var image: UIImage
    let interaction = ImageAnalysisInteraction()
    let imageView = LiveTextImageView()
    let analyzer = ImageAnalyzer()
    let configuration = ImageAnalyzer.Configuration([.text])
    
    
    func makeUIView(context: Context) -> UIImageView {
        interaction.setSupplementaryInterfaceHidden(true, animated: true)
        imageView.image = image
        imageView.addInteraction(interaction)
        imageView.contentMode = .scaleAspectFit
        return imageView
    }
    
    
    func updateUIView(_ uiView: UIImageView, context: Context) {
        Task {
            uiView.image = image
            do {
                if let image = uiView.image {
                    let analysis = try await analyzer.analyze(image, configuration: configuration)
                    interaction.analysis = analysis;
                    interaction.preferredInteractionTypes = .textSelection
                    interaction.selectableItemsHighlighted = true
                    interaction.setContentsRectNeedsUpdate()
                }
            } catch {
                // catch
            }
        }
        
    }
}

class LiveTextImageView: UIImageView {
    // Use intrinsicContentSize to change the default image size
    // so that we can change the size in our SwiftUI View
    override var intrinsicContentSize: CGSize {
        .zero
    }
}

我哪里做错了?

juzqafwq

juzqafwq1#

它看起来像一个bug。请尝试使用dispatch

let highlighted = interaction.selectableItemsHighlighted
interaction.analysis = analysis // highlighted == false
if highlighted
{
    DispatchQueue.main.async
    {
        interaction.selectableItemsHighlighted = highlighted
    }
}

如果将交互添加到UIImageView,则不需要interaction.setContentsRectNeedsUpdate()

相关问题