ios - 如何使用带有可选 UIImage 的绑定(bind)?

标签 ios swift swiftui

我有一个父 View :

@State private var myImage:UIImage? = nil

我有一个想要使用它的 subview :

@Binding var myImage: UIImage?

问题是它中断了我在该 subview 中的协调器调用:

func makeCoordinator() -> Coordinator {
    Coordinator(parent: self, myImage: $myImage)
    // error "Cannot convert value of type 'Binding<UIImage?>' to expected argument type 'Binding<UIImage>'"
}

当所有可选值都被移除后,我的 subview 中的 makeCoordinator 函数就没有错误了。处理此问题的正确方法是什么?

最佳答案

错误被抛出是因为你的 Coordinator 显然期望 myImage 不是 Binding<Optional<UIImage>>而是 Binding<UIImage> .差异很大,解决方案将取决于所需的代码设计。

1。摆脱可选

删除 ?不再处理 Optional,这可能不适合您的需要,但它是一个选项。

// in your parent
@State private var myImage: UIImage
// and child implementation
@Binding var myImage: UIImage

2。向 Coordinator 引入 Optional

添加 ?制作 Binding<UIImage>一个Binding<Optional<UIImage>> .同样,这可能不是满足您需求的最佳解决方案。

// in your Coordinator implementation
@Binding var myImage: UIImage?

3。提供具有一些默认值的新绑定(bind)

我会推荐以下内容:

func makeCoordinator() -> Coordinator {
    Coordinator(parent: self, myImage: Binding(
        get { myImage ?? UIImage() }, // or some other default value
        set { myImage = $0 }
    ))
}

解决方案实际上取决于您真正想要实现的目标。您需要决定是否真的希望 Optional 位于 Coordinator 中。

关于ios - 如何使用带有可选 UIImage 的绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65659458/

相关文章:

ios - 如何在日志中输出 CAF 文件大小?

swift - 核心数据只返回一个对象而不是所有对象

ios - SwiftUI - iOS - 当应用程序进入后台并返回事件状态时,使用 scenePhase 会导致 View 弹出

ios - SwiftUI - 如何在我的 View 中调用函数?

ios - 搜索栏不显示结果

ios - 无法从 iOS 发送 facebook apprequest,因为 FBSession.activeSession.isOpen 给出 false

ios - 如何允许用户将照片添加到其他人可以使用 Firebase 查看的应用程序

ios - 我如何判断 Springs 和 Struts 应用程序是否在 iPhone 6 模拟器中缩放?

ios - 在 Swift 中从 UITextView 获取点击的单词

SwiftUI 覆盖取消触摸