如何在Swift的注释视图中显示不同的图标?

时间:2018-12-06 05:28:26

标签: ios swift

我是新手。我正在创建带有AR批注视图的AR应用程序,在其中创建了一个places对象以显示在Annotation AR视图上,但是我无法根据AR视图中的位置显示不同的图标。我到所有地方都只有一个特定的图标。请查看我的代码以帮助我解决此问题。非常感谢你!

  

这是我的代码:

import UIKit
import AVFoundation

protocol AnnotationViewDelegate {
  func didTouch(annotationView: AnnotationView)
}


class AnnotationView: ARAnnotationView {


  var titleLabel: UILabel?
  var distanceLabel: UILabel?
  var delegate: AnnotationViewDelegate?

  var backgroundView: UIView?

  var pinImage: UIImageView?

  let pinoImage = ["bakeries", "banks", "barber", "bars", "beaches", "breweries", "cardealer", "carrepair", "church", "cinema",
                   "coffee", "college", "dentist", "dining", "doctors", "drycleaning", "fastfood", "firetruck", "fitness", "gas",
                   "grocery", "hospital", "hotel", "library", "lounges", "motorcycledealers", "musicvenues", "park", "petstore",
                   "pharmacy", "police", "postoffice", "train", "transportation", "zoo"]



  override func didMoveToSuperview() {
    super.didMoveToSuperview()

    loadUI()
  }



  func getRandomColor() -> UIColor{

    let red:CGFloat = CGFloat(drand48())
    let green:CGFloat = CGFloat(drand48())
    let blue:CGFloat = CGFloat(drand48())

    return UIColor(red:red, green: green, blue: blue, alpha: 1.0)
  }

  func loadUI() {
    titleLabel?.removeFromSuperview()
    distanceLabel?.removeFromSuperview()
    backgroundView?.removeFromSuperview()
    pinImage?.removeFromSuperview()

    backgroundView = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: 70))
    backgroundView?.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.5)

    backgroundView?.layer.cornerRadius = 10.0
    self.addSubview(backgroundView!)

    pinImage = UIImageView(frame: CGRect(x: 16, y: 8, width: 37.76, height: 54))


    pinImage?.contentMode = UIViewContentMode.scaleAspectFit
    self.backgroundView?.addSubview(pinImage!)

    let label = UILabel(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: 22.0))
    label.font = UIFont(name: "AvenirNext", size: 3)
    label.numberOfLines = 0
    label.textAlignment = .center
    label.textColor = UIColor.white
    self.backgroundView?.addSubview(label)
    self.titleLabel = label


    distanceLabel = UILabel(frame: CGRect(x: 66, y: 47, width: self.frame.size.width, height: 15.0))
    distanceLabel?.textColor = UIColor.black
    distanceLabel?.font = UIFont(name: "Montserrat-Regular", size: 12)
    self.backgroundView?.addSubview(distanceLabel!)

    if let annotation = annotation as? Place {


      titleLabel?.text = annotation.placeName
      distanceLabel?.text = String(format: "%.2f mi", annotation.distanceFromUser * 0.000621371)

      pinImage?.image =  UIImage(named: "FastFood")





    }

  }

  override func layoutSubviews() {
    super.layoutSubviews()




    backgroundView?.frame = CGRect(x: 0, y: 0, width: 170, height: 80)

    titleLabel?.frame = CGRect(x: 50, y: 8, width: self.frame.size.width - 66, height: 22.0)

    distanceLabel?.frame = CGRect(x: 50, y: 30, width: self.frame.size.width, height: 20)
    pinImage = UIImageView(frame: CGRect(x: 16, y: 8, width: 37.76, height: 54))



  }


  override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    delegate?.didTouch(annotationView: self)

  }




}
  

MapViewController

import UIKit
import MapKit
import CoreLocation

class MapViewController: BaseViewController, UITabBarDelegate{


   @IBOutlet weak var leadingConstraints: NSLayoutConstraint!


  @IBOutlet weak var mapView: MKMapView!
  fileprivate let locationManager = CLLocationManager()
  fileprivate var startedLoadingPOIs = false
  fileprivate var places = [Place]()
  fileprivate var arViewController: ARViewController!
  @IBOutlet weak var activityIndicator: UIActivityIndicatorView!

  var nearMeIndexSelected = NearMeIndexTitle()

   var place: Place?


   override func viewDidLoad() {
    super.viewDidLoad()

    mapView.delegate = self
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
    locationManager.startUpdatingLocation()
    locationManager.requestWhenInUseAuthorization()




  }




  @IBAction func showARController(_ sender: Any) {

    arViewController = ARViewController()
    arViewController.dataSource = self
    arViewController.maxVisibleAnnotations = 30
    arViewController.headingSmoothingFactor = 0.05
    arViewController.setAnnotations(places)

   self.present(arViewController, animated: true, completion: nil)


  }


}



extension MapViewController: CLLocationManagerDelegate, MKMapViewDelegate {



 func mapView(_ mapView: MKMapView,
               viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    if annotation is MKUserLocation {


      mapView.tintColor = #colorLiteral(red: 0.08235294118, green: 0.7058823529, blue: 0.9450980392, alpha: 1)




       return nil


    } else {




   let pin = mapView.view(for: annotation) ?? MKAnnotationView(annotation: annotation, reuseIdentifier: nil)
       pin.image = UIImage(named: "pins")

        return pin

   }



  }




  func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if locations.count > 0 {
      let location = locations.last!
      print("Accuracy: \(location.horizontalAccuracy)")
      if location.horizontalAccuracy < 100 {
        manager.stopUpdatingLocation()
        let span = MKCoordinateSpan(latitudeDelta: 0.013, longitudeDelta: 0.013)
        let region = MKCoordinateRegion(center: location.coordinate, span: span)
        mapView.region = region
        if !startedLoadingPOIs {
          DispatchQueue.main.async {
              self.activityIndicator.startAnimating()
          }
          startedLoadingPOIs = true

          let loader = PlacesLoader()
          loader.loadPOIS(location: location, radius: 1500) { placesDict, error in
            if let dict = placesDict {
              guard let placesArray = dict.object(forKey: "results") as? [NSDictionary] else { return }
              for placeDict in placesArray {
                let latitude = placeDict.value(forKeyPath: "geometry.location.lat") as! CLLocationDegrees
                let longitude = placeDict.value(forKeyPath: "geometry.location.lng") as! CLLocationDegrees
                let reference = placeDict.object(forKey: "reference") as! String
                let name = placeDict.object(forKey: "name") as! String
                let address = placeDict.object(forKey: "vicinity") as! String



                 let location = CLLocation(latitude: latitude, longitude: longitude)

                let place = Place(location: location, reference: reference, name: name, address: address)


                self.places.append(place)
                let annotation = PlaceAnnotation(location: place.location!.coordinate, title: place.placeName)
                DispatchQueue.main.async {
                  self.mapView.addAnnotation(annotation)
                }
              }


              DispatchQueue.main.async {
                  self.activityIndicator.stopAnimating()
                  self.mapView.isHidden = false


              }
            }
          }
        }
      }
    }
  }


}



extension MapViewController: ARDataSource {
  func ar(_ arViewController: ARViewController, viewForAnnotation: ARAnnotation) -> ARAnnotationView {
    let annotationView = AnnotationView()
    arViewController.title = "MyApp"  

    annotationView.annotation = viewForAnnotation
      annotationView.delegate = self
   annotationView.frame = CGRect(x: 0, y: 0, width: 150, height: 50)

    return annotationView
  }
}

1 个答案:

答案 0 :(得分:0)

在Mapview类中,添加以下代码

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        if (annotation is MKUserLocation) {
            return nil
        }
        let reuseId = "reuseId"

        let anView : AnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as! AnnotationView
        if let annotation = annotation as? Place {
            anView.titleLabel?.text = annotation.placeName
            anView.distanceLabel?.text = String(format: "%.2f mi", annotation.distanceFromUser * 0.000621371)
            if(annotation.placeName == "bakeries"){
                anView.pinImage?.image =  UIImage(named: "Bakery")
            }
            else{
                anView.pinImage?.image =  UIImage(named: "FastFood")
            }
        }
        anView.canShowCallout = false

        return anView
    }

通过上述方法,您可以更改图钉自定义图像