Swift 4 代理不与标签栏控制器一起工作

Swift 4 delegate is not working with tabbar controller

我有一个带有 4 个视图的标签栏视图控制器,我在第 4 个视图上设置了一个协议,并使第一个视图符合这个协议。当我从第 4 个视图调用委托方法时,它不起作用,并且第 1 个和第 4 个视图控制器之间没有 segue。

我已经定义了我的协议 并设置 weak var delegate: delegateProtocol? 然后在第一个视图控制器中我做了以下

class VC1: delegateProtocol {
    viewdidLoad(){
    var vc4 = VC4()
    VC4.delegate = self
  }

这是第 4 个视图控制器的片段

protocol SettingsDelegate: class {
    func locationDidSet(location: CLLocation)
}


class VC4: UIViewController {


  weak var delegate: SettingsDelegate?
 let controller = LocationPickerViewController()
 let navigationController = UINavigationController(rootViewController: controller)
 present(navigationController, animated: true, completion: nil)
  controller.completion = { location in
                self.location = location?.title ?? "Not found"
                defaults.set(location: location!.location, forKey: "location")
                self.tableView.reloadData()
                self.delegate?.locationDidSet(location: location!.location)
            }

这是第一个 ViewController

的片段
class MainVC: UIViewController, SettingsDelegate {
    func locationDidSet(location: CLLocation) {
        print(location.coordinate.latitude)
    }

  override func viewDidLoad() {
        super.viewDidLoad()
        settingVC = SettingsVC()
        settingVC?.delegate = self
}
}

MainVCviewDidLoad 中,您正在创建一个新的 SettingsVC 实例并将 self 分配给该实例的 属性。不是标签栏控制器的实际第四视图控制器。

tabBarController?.viewControllers数组中获取第四个视图控制器实例,并将self赋值给它的delegate属性

//主VC

override func viewDidLoad() {
  super.viewDidLoad()
  if let settingVC = self.tabBarController?.viewControllers?.first(where: { [=10=] is SettingsVC }) as? SettingsVC {
    settingVC.delegate = self
  }
}

如果视图控制器嵌入在导航控制器中。

//更新

if let settingsNavVC = self.tabBarController?.viewControllers?.first(where: { [=11=] is UINavigationController }) as? UINavigationController, 
    let settingsVC = settingsNavVC.rootViewController as? SettingsVC {
        settingsVC.delegate = self
}