如何创建没有情节提要的ViewController并将一个设置为另一个的委托?

pra*_*oje 1 delegates uiviewcontroller programmatically-created swift

这是我设置委托的第一个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()
    }
 }
Run Code Online (Sandbox Code Playgroud)

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

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

class LocationVC: UIViewController {

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

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

Wis*_*min 5

注意:我以前的答案是使用Storyboard。但是由于发问者不想使用情节提要,因此我在不使用情节提要的情况下替换了答案。[此答案是受/sf/answers/2876703021/启发的 ]

首先,删除Main.storyboard。然后在Project-> Deployment Info-> Main Interface中(选择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
}
Run Code Online (Sandbox Code Playgroud)

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

而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")


    }

}
Run Code Online (Sandbox Code Playgroud)

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

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