我有一个带有 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
}
}
最佳答案
在 MainVC
的 viewDidLoad
中,您正在创建一个新的 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/