2

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

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

我正在展示CNContactViewControllerwithinit(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)
        }
}

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

4

1 回答 1

1

SwiftUI 自己创建协调器并在上下文中提供它来表示,所以只需使用

    func makeUIViewController(context: UIViewControllerRepresentableContext<NewContactView>) -> NewContactView.UIViewControllerType {
        let vc = CNContactViewController(forNewContact: CNContact())
        vc.delegate = context.coordinator      // << here !!
        return vc
    }
于 2020-07-01T09:31:00.160 回答