【问题标题】:CNContactViewControllerDelegate not called when using the Coordinator pattern in SwiftUI在 SwiftUI 中使用协调器模式时未调用 CNContactViewControllerDelegate
【发布时间】:2020-07-01 08:49:05
【问题描述】:

我已经研究这个问题好几天了,似乎 SwiftUI 的相对“新奇”似乎对我没有帮助。

我的直觉是我以某种方式使用 CNContactViewControllerDelegate 错误,但 Apple 的文档以及其他关于 SO 的问题都让它看起来应该有效。也许,这也是由.sheet 的处理引起的,但我也无法隔离问题。不将 NewContactView 包裹在 NavigationView 内也没有任何区别,并删除了默认导航栏(如预期的那样)。

我将CNContactViewControllerinit(forNewContact:) 一起显示,以使应用程序的用户能够添加新联系人。坚持下去,一切正常,但是,似乎没有一个委托的函数被调用。

iOS 13 中引入的“滑动关闭”手势关闭模式既不会调用委托函数,也不会使用CNContactViewController 提供的导航按钮。

import Foundation
import SwiftUI
import ContactsUI

struct NewContactView: UIViewControllerRepresentable {
    class Coordinator: NSObject, CNContactViewControllerDelegate, UINavigationControllerDelegate {

        func contactViewController(_ viewController: CNContactViewController, didCompleteWith contact: CNContact?) {
            if let c = contact {
                self.parent.contact = c
            }
            viewController.dismiss(animated: true)
        }
        
        func contactViewController(_ viewController: CNContactViewController, shouldPerformDefaultActionFor property: CNContactProperty) -> Bool {
            return true
        }

        var parent: NewContactView

        init(_ parent: NewContactView) {
            self.parent = parent
        }
    }

    @Binding var contact: CNContact

    init(contact: Binding<CNContact>) {
        self._contact = contact
    }

    typealias UIViewControllerType = CNContactViewController

    func makeCoordinator() -> Coordinator {
        return Coordinator(self)
    }

    func makeUIViewController(context: UIViewControllerRepresentableContext<NewContactView>) -> NewContactView.UIViewControllerType {
        let vc = CNContactViewController(forNewContact: CNContact())
        vc.delegate = makeCoordinator()
        return vc
    }

    func updateUIViewController(_ uiViewController: NewContactView.UIViewControllerType, context: UIViewControllerRepresentableContext<NewContactView>) {
    }
}

用于显示控制器的视图代码如下所示:

.sheet(isPresented: self.$viewModel.showNewContact, onDismiss: { self.viewModel.fetchContacts() }) {
        NavigationView() {
                NewContactView(contact: self.$viewModel.newContact)
        }
}

感谢您的任何指点!可悲的是,橡皮鸭并没有帮助......

【问题讨论】:

    标签: ios swiftui uikit cncontactviewcontroller


    【解决方案1】:

    SwiftUI 自己创建协调器并将其提供给上下文中的可表示,所以只需使用

        func makeUIViewController(context: UIViewControllerRepresentableContext<NewContactView>) -> NewContactView.UIViewControllerType {
            let vc = CNContactViewController(forNewContact: CNContact())
            vc.delegate = context.coordinator      // << here !!
            return vc
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-27
      • 1970-01-01
      • 2019-02-09
      • 2019-11-28
      • 2020-10-21
      • 2020-03-15
      相关资源
      最近更新 更多