如何在 Swift 的 MKMapView 中用下一个视图控制器的新值替换旧值?

How to replace old value with new value from next view controller in MKMapView in Swift?

我有两个地图视图控制器,在第一个视图控制器中,我正在获取当前位置并自动填充一些值并将它们显示在相关的文本字段中。

在第二个视图控制器中,我正在搜索新位置并使用 DataEnteredDelegate 方法将其位置值发送到第一个视图控制器,现在如何替换第一个视图控制器中当前位置值中的委托方法值。

这里我得到第二个视图控制器值:

func userDidEnterInformation(info: [String]) {
    print("zoom map address viewcontroller data \(info)")
}

打印:zoom map address viewcontroller data '["560066", "Auto Nagar", "Bangalore"]'

如何替换 560066 in self.pincodeField.text and Auto Nagar in self.streetField.text and Bangalore in self.cityField.text 在第一个视图控制器中

首先查看控制器代码:

class ProfileAddressViewController: UIViewController, CLLocationManagerDelegate, UISearchBarDelegate, DataEnteredDelegate {


@IBOutlet weak var pincodeField: UITextField!
@IBOutlet weak var cityField: UITextField!
@IBOutlet weak var streetField: UITextField!
@IBOutlet weak var storeNoField: UITextField!
@IBOutlet weak var colonyField: UITextField!
@IBOutlet weak var landmarkField: UITextField!

@IBOutlet weak var mapView: MKMapView!
let annotation = MKPointAnnotation()

let locationManager = CLLocationManager()
var latitude: String?
var logitude: String?
override func viewDidLoad() {
    super.viewDidLoad()

    self.locationManager.requestAlwaysAuthorization()
    if CLLocationManager.locationServicesEnabled() {
        locationManager.delegate = self

        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        locationManager.startUpdatingLocation()
    }
}

override func viewWillAppear(_ animated: Bool) {
    self.navigationController?.navigationBar.isHidden=true;
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.triggerTouchAction(_:)))
    mapView.addGestureRecognizer(tapGesture)
}
@objc func triggerTouchAction(_ sender: UITapGestureRecognizer) {
    print("Please Help!")

    let viewController = self.storyboard?.instantiateViewController(withIdentifier: "NewZoomAddressViewController") as! NewZoomAddressViewController;
        viewController.delegate = self

    viewController.zipName = self.pincodeField.text
    viewController.sublocalityName = self.colonyField.text
    viewController.localityName = self.cityField.text
        self.navigationController?.pushViewController(viewController, animated: true);
}

func userDidEnterInformation(info: [String]) {
    print("zoom map address viewcontroller data \(info)")
}
@IBAction func submitButtonClicked(_ sender: UIButton) {
    self.view.endEditing(true)
        let viewController = self.storyboard?.instantiateViewController(withIdentifier: "NewZoomAddressViewController") as! NewZoomAddressViewController;
        self.navigationController?.pushViewController(viewController, animated: true);
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    print(error)
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let _: CLLocationCoordinate2D = manager.location?.coordinate else { return }

    let userLocation :CLLocation = locations[0] as CLLocation
    latitude = "\(userLocation.coordinate.latitude)"
    logitude = "\(userLocation.coordinate.longitude)"
    let geocoder = CLGeocoder()
    geocoder.reverseGeocodeLocation(userLocation) { (placemarks, error) in
        if (error != nil){
            print("error in reverseGeocode")
        }
        let placemark = placemarks! as [CLPlacemark]

        if placemark.count>0{
            let placemark = placemarks![0]
            print(placemark.administrativeArea!)
            print(placemark.country!)
            let placemarkDictonary: NSDictionary=placemark.addressDictionary as! NSDictionary
            self.pincodeField.text=placemarkDictonary["ZIP"] as? String
            self.cityField.text=placemarkDictonary["City"] as? String
            self.streetField.text=placemarkDictonary["Street"] as? String
            self.colonyField.text=placemarkDictonary["SubLocality"] as? String
            self.landmarkField.text=placemarkDictonary["SubThoroughfare"] as? String
        }
    }

    let center = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude)
    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
    mapView.setRegion(region, animated: true)
    // Drop a pin at user's Current Location
    let myAnnotation: MKPointAnnotation = MKPointAnnotation()
    myAnnotation.coordinate = CLLocationCoordinate2DMake(userLocation.coordinate.latitude, userLocation.coordinate.longitude);
    myAnnotation.title = "Current location"
    mapView.addAnnotation(myAnnotation)
    locationManager.stopUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    switch status {
    case .notDetermined:
        print("User still thinking")
    case .denied:
        print("User hates you")
    case .authorizedWhenInUse:
        locationManager.stopUpdatingLocation()
    case .authorizedAlways:
        locationManager.startUpdatingLocation()
    case .restricted:
        print("User dislikes you")
    }
}
}

下一个视图控制器代码:

protocol DataEnteredDelegate: class {
func userDidEnterInformation(info: [String])
}
class NewZoomAddressViewController: UIViewController {
weak var delegate: DataEnteredDelegate? = nil
var userModel : ProfileModel?

var zipName: String?
var localityName: String?
var sublocalityName: String?

@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var addressLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    print("in Zoom map VC")
    mapView.delegate = self
    addressLabel.text = "\(self.sublocalityName!) \(localityName!) \(self.zipName!)"
}

@IBAction func confirmBtn(_ sender: Any) {
    delegate?.userDidEnterInformation(info: [zipName!,sublocalityName!, localityName!])
    self.navigationController?.popViewController(animated: true)
}

你快到了。只需将值设置为 userDidEnterInformation(:) func:

中的文本字段
func userDidEnterInformation(info: [String]) {
   self.pincodeField.text = info[0]
   self.streetField.text = info[1]
   self.cityField.text = info[2]
}

但是,使用数字访问String数组下标可能会出错,我建议您采用以下方法:

  1. 您应该为返回的信息定义类似模型的东西,而不是使用字符串数组。我建议你在某处添加以下结构:
struct DataEnteredModel {
   let pinCode: String
   let streetField: String
   let cityField: String
}
  1. 将委托方法中的函数类型从 func userDidEnterInformation(info: [String]) 更改为 func userDidEnterInformation(info: DataEnteredModel)

  2. confirmBtn(_:9中这样调用委托函数:

@IBAction func confirmBtn(_ sender: Any) {
    guard
        let zipName = zipName,
        let sublocalityName = sublocalityName,
        let localityName = localityName 
        else { return }
    let enteredData = DataEnteredModel(pinCode: zipName, streetField: sublocalityName, cityField: localityName)
    delegate?.userDidEnterInformation(info: enteredData)
}
  1. 最后,在 ProfileAddressViewController 中的 userDidEnterInformation 方法中,您必须执行以下操作:
func userDidEnterInformation(info: DataEnteredModel) {
    self.pincodeField.text = info.pinCode
    self.streetField.text = info.streetField
    self.cityField.text = info.cityField
}

应该就是这样了,有什么问题,尽管问!