I would like to call a func from another viewcontroller.
here with the code in pubListViewController: It is working fine.
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
}
now I try to call it in another viewcontroller as below, but it shows nothing.
override func viewDidAppear(_ animated: Bool) {
pubListViewController().navigationBarTitleImage(imageTitle: "addTitle")
}
When you're using notation like that pubListViewController()
you call free empty initializer of pubListViewController
which creates new instance of class pubListViewController
, but you do already have one in your screens flow I bet, so all changes made by function you're calling later are being applied to invisible instance of pubListViewController
.
To solve this problem you need a reference actually displaying instance of pubListViewController
from your another viewcontroller
In another viewcontroller
you can create a property of type pubListViewController
, then before showing another viewcontroller
set its property to self
, and use that property from wherever you want in 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")
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.