如何在没有故事板的情况下创建 ViewControllers 并将一个设置为另一个的委托?

How to create ViewControllers without storyboard and set one as delegate of the other one?

这是我设置委托的第一个 VC:

class DiscoverVC: UIViewController, SetLocationDelegate {
    var name = ""
    let loc = LocationVC()
     override func viewDidLoad() {
        super.viewDidLoad()
        self.loc.delegate = self
     }

      func getLocation(loc: String) {
        self.name = loc
        self.tableView.reloadData()
    }
 }

这是我通过委托获取数据的第二个视图控制器:

protocol SetLocationDelegate: class {
    func getLocation(loc: String)
}

class LocationVC: UIViewController {

    weak var delegate: SetLocationDelegate?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate?.getLocation(loc: "Sam")
    }
}

每当我尝试传递数据时,它都不会调用该方法,委托也不会被调用。急需帮助。

注意:我之前的回答是使用 Storyboard。但是由于提问者不想使用故事板,所以我在不使用故事板的情况下替换了我的答案。 [此答案的灵感来自 ]

首先,删除Main.storyboard。然后在项目 -> 部署信息 -> 主界面(选择 LaunchScreen 而不是 'Main')

然后在 AppDelegate.swift 上使用以下内容修改 didFinishLaunching:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    window = UIWindow(frame: UIScreen.main.bounds)
    let discoverVC = DiscoverVC() as UIViewController
    let navigationController = UINavigationController(rootViewController: discoverVC)
    navigationController.navigationBar.isTranslucent = false
    self.window?.rootViewController = navigationController
    self.window?.makeKeyAndVisible()

    return true
}

DiscoverVC.swift 看起来像这样:

import UIKit

class DiscoverVC: UIViewController, SetLocationDelegate {

    var name = ""

    // to instantiate LocationVC once only for testing
    var notVisted = true

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = .yellow 
        loadLocationVCOnlyOnce()
    }

    func loadLocationVCOnlyOnce() {
        // only visit one
        guard notVisted else { return }

        let locationVC = LocationVC()
        locationVC.delegate = self 
        self.navigationController?.pushViewController(locationVC, animated: true)

    }

    func getLocation(loc: String) {
        self.name = loc
        print(name)
    }
}

LocationVC 看起来像这样:

import UIKit

protocol SetLocationDelegate: class {
    func getLocation(loc: String)
}

class LocationVC: UIViewController {

    weak var delegate: SetLocationDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = .cyan 
        self.delegate?.getLocation(loc: "Sam")


    }

}

启动时,它会自动从 DiscoverVC(黄色背景)移动到 LocationVC(青色背景)。

然后单击顶部的 'Back' 按钮后,您将看到 'Sam' 打印在您的控制台中。您的视图返回到 DiscoverVC(黄色背景)。