简体   繁体   中英

How can I call a method in one view controller from another?

I thought this would be simple, but I'm really struggling with it. I have a map view in a tab bar controller, and I have a viewController that when you tap a button, it is supposed to save the user's coordinates and put an annotation on the map. I thought I could just make a boolean newPost , and set it as true, and then in the viewDidLoad method for my map view, say,

if newPost {
    var newAnnotation = MKPointAnnotation()
    var newPostCoordinate = CLLocationCoordinate2DMake(userPosts.last!.postLatitude, userPosts.last!.postLongitude)
    newAnnotation.coordinate = newPostCoordinate
    newAnnotation.title = userPosts.last!.postTitle
    mainMapView.addAnnotation(newAnnotati
    newPost = false
}

Unfortunately, the mapView doesn't reload when I go back to it after going to the new post viewController, so the viewDidLoad method doesn't get called again.

So instead, I created a new method, and tried to call it when the post button on the new post viewController is tapped. This is where I got stuck. I thought it would just be:

mapViewController.theMethodIWantToRun()

but I end up with a "missing argument for parameter #1 in call" error. My method doesn't have any arguments or return anything, so I don't think I should need arguments...

I feel like this is a pretty dumb question, but if I could figure it out, I wouldn't be here.

If you think there's a better way to do what I'm trying to do, feel free to let me know! Thanks!

The easiest way to do that is to move your newPost condition in viewWillAppear method. Otherwise the best approach to send data between controllers is by using delegation pattern

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM