ios - Swift 4 委托(delegate)不适用于标签栏 Controller

标签 ios swift uitabbarcontroller protocols

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

我已经定义了我的协议(protocol) 并设置 weak var delegate: delegateProtocol? 然后在第一个 View Controller 中我做了以下操作

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

这是第四个 View Controller 的片段

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 分配给该实例的属性.不是标签栏 Controller 的实际第四 View Controller 。

tabBarController?.viewControllers 数组中获取第四个 View Controller 实例,并将 self 分配给它的 delegate 属性

//主VC

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

如果 View Controller 嵌入在导航 Controller 中。

//更新

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

关于ios - Swift 4 委托(delegate)不适用于标签栏 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57534467/

相关文章:

android - 当应用程序未运行(iphone/android)时,在远程触发器上创建(重复高音)警报,就像查找我的 iPhone 一样

ios - 在 Swift 中刷新 NSFetchedResultController

ios - 将 ReactiveCocoa 中的信号组合成一个在所有变化时触发的新信号

ios - 每次单击 'more' 选项时导航回选项卡选项表

ios - Swift:观察 NSUserDefaults 时出现 EXC_BAD_ACCESS

ios - 如何使用其他按钮添加到 UIStepper 值?

ios - UITextView 的视差效果使顶部的 UIImageView 在 Swift 中缩小并消失

ios - TableviewController/行/图像的问题

ios - 为什么我在 iOS 6 中切换 tabBar Items 数组时出现黑屏?

ios - 访问另一个 View 的元素(iOS - 标签栏 Controller )