无法将坐标从带有mapKit的ViewController发送到带有委托的另一个viewController [英] Unable to send coordinates from ViewController with mapKit to another viewController with delegate

查看:49
本文介绍了无法将坐标从带有mapKit的ViewController发送到带有委托的另一个viewController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Swift和iOS开发的新手.我有一个问题,其中我有三个通过选项卡栏导航控制器连接的viewControllers.第一个viewController目前为空,尚未使用.在secondViewController中,我使用天气API中的数据更新UI.在thirdViewController中,我有一张地图.当我访问地图时,我需要坐标来更新secondViewController中的网址.

I am new to Swift and iOS development. I have an issue where I have three viewControllers connected via a tab bar navigation controller. The first viewController is empty for now and not in use. In the secondViewController I update the UI with data from a weather API. In the thirdViewController I have a map. When I access the map I need the coordinates to update the url in the secondViewController.

我要实现的是在ThirdViewController中检索当前的纬度和经度(没问题),但是我无法通过委托发送这些值以触发secondViewController中的函数,从而更新那里的变量.secondViewController中的委托函数不会被触发.我究竟做错了什么?还是有可能这样做?

What I'm trying to achieve is retrieving the current latitude and longitude in the thirdViewController (no problem), but I'm unable to send these values through a delegate in order to trigger the function in the secondViewController and thus update the variables in there. The delegate function in the secondViewController just doesn't get triggered. What am I doing wrong? Or is it even possible to do this way?

两个viewController的代码如下:

The code is as follows for both viewControllers:

secondViewController(这是我在thirdViewController中需要来自地图的值的地方)

secondViewController (this is where I need the values from the map in thirdViewController)

import UIKit

class SecondViewController: UIViewController, MapViewControllerDelegate {

    var forecastData: [ForecastData] = []
    var currentLat: String = "59.911166"
    var currentLon: String = "10.744810"
    
    @IBOutlet weak var tableView: UITableView!
    
    var weatherManager = WeatherManager()
    var mapViewController = ThirdViewController()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        mapViewController.delegate = self
        weatherManager.delegate = self
        weatherManager.fetchWeather(latitude: currentLat, longitude: currentLon)
        tableView.backgroundView = UIImageView(image: UIImage(named: "background"))
        tableView.dataSource = self
        tableView.register(UINib(nibName: "WeatherCell", bundle: nil), forCellReuseIdentifier: "WeatherCell")
        
    }
    
    func viewDidAppear() {
        weatherManager.fetchWeather(latitude: currentLat, longitude: currentLon)
        
    }
    
    
    // THIS FUNCTION SHOULD BE TRIGGERED BUT DOESN'T
    
    func mapViewController(latitude: String, longitude: String) {
        currentLat = latitude
        currentLon = longitude
        print(currentLat)
        print(currentLon)
        print("DELEGATE METHOD TRIGGERED")
    }

}

//MARK: - WeatherManagerDelegate

extension SecondViewController: WeatherManagerDelegate {
    
    func didUpdateWeather(_ weatherManager: WeatherManager, weather: WeatherModel) {
        
        forecastData.append(ForecastData(timespan: "Nå", precipitation: "", tempOrWeather: "Temperatur", tempWeatherLabel: "\(weather.temperatureNow)" + " " + "\(weather.tempUnits)"))
        
        forecastData.append(ForecastData(timespan: "Neste Time", precipitation: "\(weather.precipitationNext1H)" + " " + "\(weather.precipUnits)", tempOrWeather: "vær", tempWeatherLabel: String(weather.conditionNext1H) ))
        
        forecastData.append(ForecastData(timespan: "Neste 6 timer", precipitation: "\(weather.precipitationNext6H)" + " " + "\(weather.precipUnits)", tempOrWeather: "vær", tempWeatherLabel: String(weather.conditionNext6H)))
        
        forecastData.append(ForecastData(timespan: "Neste 12 timer", precipitation: "", tempOrWeather: "vær",  tempWeatherLabel: String(weather.conditionNext12H)))
        
        DispatchQueue.main.async {
            self.tableView.reloadData()
        }
        
    }
    
    func didFailWithError(error: Error) {
        print(error)
    }
}

extension SecondViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return forecastData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "WeatherCell", for: indexPath)
        as! WeatherCell
        cell.TimeframeLabel.text = forecastData[indexPath.row].TimeframeLabel
        cell.TempLabel.text = forecastData[indexPath.row].TempLabel
        cell.WeatherCodeLabel.text = forecastData[indexPath.row].WeatherCodeLabel
        cell.PrecipitationLabel.text = forecastData[indexPath.row].PrecipitationLabel
        return cell
    }
}

thirdViewController(这是我尝试通过委托传递坐标值的地方)

thirdViewController (this is where I try to pass the coordinates values through the delegate)

import UIKit
import MapKit
import CoreLocation

protocol MapViewControllerDelegate {
    func mapViewController(latitude: String, longitude: String)
}

class ThirdViewController: UIViewController, MKMapViewDelegate {
    
    var currentLat = ""
    var currentLon = ""
    @IBOutlet weak var mMapView: MKMapView!
    fileprivate let locationManager: CLLocationManager = CLLocationManager()
    var delegate: MapViewControllerDelegate?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.requestWhenInUseAuthorization()
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.distanceFilter = kCLDistanceFilterNone
        locationManager.startUpdatingLocation()
        
        mMapView.showsUserLocation = true
               
        currentLat = String((locationManager.location?.coordinate.latitude)!)
        currentLon = String((locationManager.location?.coordinate.longitude)!)
        
        print(currentLat)
        print(currentLon)
        
        //delegate?.mapViewController(latitude: "TESTlon", longitude: "TESTlati")
    }
    
    override func viewDidAppear(_ animated: Bool) {
        updateWeatherView()
    }
    
    // THIS SHOULD TRIGGER THE DELEGATE FUNCTION IN SECOND VIEW CONTROLLER AND PASS THE DATA ALONG
    func updateWeatherView() {
        delegate?.mapViewController(latitude: "TESTlon", longitude: "TESTlati")
    }
    
}


我尝试了不同的方法,但是似乎没有任何效果,secondViewController中的委托函数只是没有被触发.同样,我对此很陌生,所以也许这很简单.在此先感谢您的帮助!另外,如果有帮助,下面是我的故事板的屏幕截图:

I have tried different thing, but nothing seems to work, the delegate function in secondViewController just doesn't get triggered. Again, I am very new to this so maybe it's a simple thing. Thanks in advance for any help! Also, here is a screenshot of my storyboard if it can help:

推荐答案

就像@Duncan C所说的那样

As @Duncan C said, doing

var weatherManager = WeatherManager()
var mapViewController = ThirdViewController()

只是创建这些视图控制器的新实例-这些与您已经拥有的控制器完全无关.当然,如果您执行 mapViewController.delegate = self ,则是在设置 mapViewController 的委托...,但是 mapViewController 不是您想要的视图控制器.

just creates a new instance of those view controllers -- these are completely unrelated to the ones you already have. Sure, if you do mapViewController.delegate = self, you are setting mapViewController's delegate... but mapViewController is not the view controller that you want.

要获取所需的视图控制器,您可以访问选项卡栏控制器的视图控制器(在情节提要中将它们自动为您创建),然后选择合适的视图控制器:

To get the view controller that you want, you can access the tab bar controller's view controllers (these are automatically created for you when you make them in the storyboard), and pick the right one:

if 
    let viewControllers = self.tabBarController?.viewControllers, 
    viewControllers.count >= 3,
    let thirdViewController = viewControllers[2] as? ThirdViewController /// [2] because that's the third view controller in the array, which is the one you want
{
    thirdViewController.delegate = self
}

self.tabBarController 可能为nil,因此您需要解开包装.然后,您应确保有3个以上的视图控制器.最后,您需要将所需的视图控制器( self.tabBarController?.viewControllers [2] )强制转换为 ThirdViewController .然后,您可以将委托设置为该视图控制器.

self.tabBarController could be nil, so you need to unwrap it. Then, you should make sure that there are more than 3 view controllers. Finally, you need to cast the view controller you need (self.tabBarController?.viewControllers[2]) to ThirdViewController. You can then set the delegate to that view controller.

这篇关于无法将坐标从带有mapKit的ViewController发送到带有委托的另一个viewController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆