0

我正在使用这里的教程https://www.hackingwithswift.com/quick-start/swiftui/how-to-convert-a-swiftui-view-to-an-image

extension View {
    func snapshot() -> UIImage {
        let controller = UIHostingController(rootView: self)
        let view = controller.view

        let targetSize = controller.view.intrinsicContentSize
        view?.bounds = CGRect(origin: .zero, size: targetSize)
        view?.backgroundColor = .clear

        let renderer = UIGraphicsImageRenderer(size: targetSize)

        return renderer.image { _ in
             view?.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
        }
    }
}

我想将此代码应用于

Text("Hello world!")
                       .swipeActions(edge: .leading) {
                            Button {
                                total += 1
                            } label: {
                                Label("Add", systemImage: "plus.circle")
                            }
                            .tint(.indigo)
                        }
                        .swipeActions(edge: .trailing) {
                            Button {
                                total -= 1
                            } label: {
                                Label {
                                    Text("Hello")
                                } icon: {
                                    Image(uiImage:       
                                        Text("World")
                                            .foregroundColor(.red)
                                            .snapshot() // Here is usage
                                    ) 
                                }
                            }
                        }

但结果我在这种特殊情况下得到了空的灰色按钮(并且在我的真实代码运行时错误中关于重绘时间的改变)

怎么了?

4

0 回答 0