swift 从另一个 viewcontroller 调用函数

swift call a func from another viewcontroller

我想调用另一个函数 viewcontroller。

此处使用 pubListViewController 中的代码:工作正常。

    override func viewDidAppear(_ animated: Bool) {
    navigationBarTitleImage(imageTitle: "IconTitle")
}

func navigationBarTitleImage(imageTitle: String) {
    // 1
    //        let nav = self.navigationController?.navigationBar

    // 2
    //        nav?.barStyle = UIBarStyle.black
    //        nav?.tintColor = UIColor.yellow

    // 3
    let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
    imageView.contentMode = .scaleAspectFit

    // 4
    let image = UIImage(named: imageTitle)
    imageView.image = image

    // 5
    navigationItem.titleView = imageView
}

现在我尝试在另一个 viewcontroller 中调用它,如下所示,但它什么也没显示。

    override func viewDidAppear(_ animated: Bool) {
    pubListViewController().navigationBarTitleImage(imageTitle: "addTitle")
}

当你使用像 pubListViewController() 这样的符号时,你调用了 pubListViewController 的免费空初始值设定项,它创建了 class pubListViewController 的新实例,但你已经有了我敢打赌,您的屏幕中有一个流,因此您稍后调用的函数所做的所有更改都将应用于 pubListViewController.

的不可见实例

要解决此问题,您需要一个实际显示 另一个 viewcontroller

实例的参考

another viewcontroller 中你可以创建一个 pubListViewController 类型的 属性,然后在显示 another viewcontroller 之前将其 属性 设置为 self,并在 another viewcontroller.

中的任意位置使用 属性
class PubListViewController: UIViewController {
  func prepareForSegue(/**/){ // actually do that in the place where you showing your another viewcontroller, I don't know if you're using segues or not
    destinationViewController.parentPubListViewController = self
  }
}

class AnotherViewController: UIViewController {
  // declare property (weak and optional to avoid crashes or memory leaks if you forget to set that property from parent view controller
  weak var parentPubListViewController: PubListViewController?

  // use it anywhere you need
  parentPubListViewController?.navigationBarTitleImage(imageTitle: "addTitle")
}