【问题标题】:swift call a func from another viewcontroller从另一个视图控制器快速调用一个函数
【发布时间】:2018-03-10 06:52:19
【问题描述】:

我想从另一个视图控制器调用一个函数。

这里有 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
}

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

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

【问题讨论】:

  • 您是否使用故事板?
  • 你想要什么最终的操作?您的函数实际上正在调用,但它使用实例 pubListViewController()?正是你想要的?
  • 如果您正在创建视图控制器的新实例并访问其功能。它不会反映在您的 UI 中。
  • 我只想使用第一个视图控制器中的函数来设置第二个视图控制器的标题图像,而不是将函数从第一个 VC 复制到第二个 VC。我做错了吗?
  • 你在使用 segues 吗?

标签: swift function call viewcontroller


【解决方案1】:

当您使用 pubListViewController() 之类的符号时,您会调用 pubListViewController 的免费空初始化程序,它会创建类 pubListViewController 的新实例,但我敢打赌,您的屏幕流程中已经有了一个,所以所有更改都已完成您稍后调用的函数将应用于pubListViewController 的不可见实例。

要解决这个问题,您需要一个实际显示来自您的另一个视图控制器

的pubListViewController 实例的引用

在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")
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    • 2019-09-11
    相关资源
    最近更新 更多