【问题标题】:Swift 3 - MKPointAnnotation custom ImageSwift 3 - MKPointAnnotation 自定义图像
【发布时间】:2017-05-09 18:40:41
【问题描述】:

这是我的代码,我想添加一个自定义图钉(.png 文件)而不是红色图钉。我尝试使用 MKPinAnnotationView 和 MKAnnotationView 但我无法添加坐标、字幕和标题。我是 iOS 开发新手。

override func viewDidLoad() {
    super.viewDidLoad()
    // Handle the text field’s user input through delegate callbacks.
    commentTextField.delegate = self

    coreLocationManager.delegate = self
    //desired accuracy is the best accuracy, very accurate data for the location
    coreLocationManager.desiredAccuracy = kCLLocationAccuracyBest
    //request authorization from the user when user using my app
    coreLocationManager.requestWhenInUseAuthorization()

    coreLocationManager.startUpdatingLocation()

    dbRef = FIRDatabase.database().reference()

    struct Location {
        let title: String
        let latitude: Double
        let longitude: Double
        let subtitle: String
    }
    // Locations array
    let locations = [
        Location(title: "Dio Con Dio",    latitude: 40.590130, longitude: 23.036610,subtitle: "cafe"),
        Location(title: "Paradosiako - Panorama", latitude: 40.590102, longitude: 23.036180,subtitle: "cafe"),
        Location(title: "Veranda",     latitude: 40.607740, longitude: 23.103044,subtitle: "cafe")
    ]

    for location in locations {
        let annotation = MKPointAnnotation()

        annotation.title = location.title
        annotation.coordinate = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude)
        annotation.subtitle = location.subtitle

        map.addAnnotation(annotation)
    }



}

【问题讨论】:

    标签: ios swift mapkit mkpointannotation


    【解决方案1】:

    您需要将您的视图控制器指定为地图视图的委托(在 IB 中或以编程方式在 viewDidLoad 中指定,然后 (a) 指定您遵守 MKMapViewDelegate 协议;并且 (b) 实现mapView(_:viewFor:):

    extension ViewController: MKMapViewDelegate {
        func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
            let identifier = "MyPin"
    
            if annotation is MKUserLocation {
                return nil
            }
    
            var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
    
            if annotationView == nil {
                annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier)
                annotationView?.canShowCallout = true
                annotationView?.image = UIImage(named: "custom_pin.png")
    
                // if you want a disclosure button, you'd might do something like:
                //
                // let detailButton = UIButton(type: .detailDisclosure)
                // annotationView?.rightCalloutAccessoryView = detailButton
            } else {
                annotationView?.annotation = annotation
            }
    
            return annotationView
        }
    }
    

    有关详细信息,请参阅Location and Maps Programming Guide: Creating Annotation Views from Your Delegate Object。代码 sn-ps 在 Objective-C 中,但它描述了基本过程。

    【讨论】:

      【解决方案2】:

      最后我自己做到了!

      ViewController.swift

          //
          //  ViewController.swift
      
          //
          //  Created by Alexandros Andreadis on 19/04/2017.
          //  Copyright © 2017 Alexandros Andreadis. All rights reserved.
          //    
          import UIKit
          import MapKit
          import CoreLocation
          import FirebaseDatabase
      
          class RateViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, CLLocationManagerDelegate, MKMapViewDelegate{
          let pin = UIImage(named: "pin")
          func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?
              {
      
                  if let annotation = annotation as? Locations{
                      if let view = mapView.dequeueReusableAnnotationView(withIdentifier: annotation.identifier){
                          return view
                      }else{
                          let view = MKAnnotationView(annotation: annotation, reuseIdentifier: annotation.identifier)
                          view.image = pin
                          view.isEnabled = true
                          view.canShowCallout = true
                          //view.leftCalloutAccessoryView = UIImageView(image: pin)
                          return view
                      }
                  }
                  return nil
              }
              override func viewDidLoad() {
                  super.viewDidLoad()
      
                  mapView.delegate = self 
      
                  mapView.addAnnotations(locations)
      
      
      
              }
      
      
          }
      

      Locations.swift

      //
      //  Locations.swift
      
      //
      //  Created by Alexandros Andreadis on 10/05/2017.
      //  Copyright © 2017 Alexandros Andreadis. All rights reserved.
      //
      
      import UIKit
      import MapKit
      
      class Locations: NSObject, MKAnnotation {
          // required coordinate, title, and the reuse identifier for this annotation
          var identifier = "locations"
          var title: String?
          var coordinate: CLLocationCoordinate2D
          //initializer taking a name, a latitude and longitude to populate the title and coordinate for each instance of this object
          init(name:String,lat:CLLocationDegrees,long:CLLocationDegrees){
              title = name
              coordinate = CLLocationCoordinate2DMake(lat, long)
          }
      
      }
      // Creating the list of the places that will be pinned in map
      class LocationList: NSObject {
          var Location = [Locations]()
          override init(){
              Location += [Locations(name: "Dio Con Dio", lat: 40.590130, long: 23.036610)]
              Location += [Locations(name: "Paradosiako - Panorama", lat: 40.590102, long:23.036180)]
              Location += [Locations(name: "Veranda",  lat: 40.607740, long: 23.103044)]
              Location += [Locations(name: "Markiz",  lat: 40.634252, long: 22.936276)]
              Location += [Locations(name: "Moi Lounge Bar",  lat: 40.653481, long: 22.994131)]
              Location += [Locations(name: "Boulevard Lounge Bar",  lat: 40.658462, long: 22.983198)]
              Location += [Locations(name: "Ernést Hébrard",  lat: 40.631829, long: 22.941014)]
              Location += [Locations(name: "Tribeca - All Day & Night Bar",  lat: 40.631029, long: 22.942396)]
      
          }
      }
      

      【讨论】:

      • 如果dequeueReusableAnnotationView 成功,请确保在返回注解视图之前设置annotation 属性。事实上,您重复使用的注释视图将无法正常工作。
      • @Rob 谢谢!另一个问题。每次用户触摸引脚时,我如何获取引脚名称并将其分配给 UILabel?例如,如果他触摸名称:Dio Con Dio pin,我希望将此名称分配给 UILabel,如果他触摸另一个引脚,我希望 UILabel 获取最后一次触摸的引脚的字符串值。
      • 你可以实现mapView(_:didSelect:) 并在那里做。
      • @Rob 对不起,错误.. 没关系
      • @Rob 嘿,Rob。我编写了该代码以获取 pin 的名称:annotationTouched = (String(describing: annotation.title)) print (annotationTouched),但它打印 Optional("Dio Con Dio") .. 我只想要 Dio Con Dio 字。怎么办?
      【解决方案3】:
      func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
      
      let identifier = "MyPin"
      
      if annotation.isKindOfClass(MKUserLocation) {
          return nil
      }
      
      let detailButton: UIButton = UIButton(type: UIButtonType.DetailDisclosure)
      
      if let annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) {
          annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "pin")
          annotationView.canShowCallout = true
          annotationView.image = UIImage(named: "custom_pin.png")
          annotationView.rightCalloutAccessoryView = detailButton
      }
      else {
          annotationView.annotation = annotation
      }
      
      return annotationView }
      

      【讨论】:

      • 这是 Swift 2.3,现在人们一般都在写 Swift 3 代码。此外,您的annotationView 变量需要在if 语句的范围之外定义。并且您希望在创建注释视图时使用与创建它时相同的标识符。并且关于创建注释视图的逻辑是向后的(只有在出队失败时才应该实例化一个新的注释视图)。
      • 谢谢,这真的很有帮助。 :)
      【解决方案4】:

      使用这个方法: 可选 func mapView(_ mapView: MKMapView, didAdd 视图:[MKAnnotationView])

      对我来说很好(我的环境:Xcode 9.4.1 和 iOS 11.4.1)

      例子:

      func mapView(_ mapView: MKMapView,
                   didAdd views: [MKAnnotationView])
      {
          //views[0] = just added MKAnnotationView
          let pic = UIImage(named: "abc.jpg")
      
          views[0].image = pic
          views[0].layer.cornerRadius = (views[0].frame.size.width) / 2
          views[0].clipsToBounds = true
      
          print("fafafjejowfjpeawijoefaw")
      }
      

      【讨论】:

        【解决方案5】:

        我是这样添加的

            func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) {
              let sourceView = views.first
              sourceView?.image = UIImage(named: "Bus")
              let destinationView = views.last
              destinationView?.image = UIImage(named: "Home")
           }
        

        【讨论】:

          【解决方案6】:

          SWIFT 5

          let pointAnnotation = MKPointAnnotation()
          
          override func viewDidLoad()
          {
             mapVw.delegate = self
           pointAnnotation.coordinate = CLLocationCoordinate2D(latitude: yourLatitude, longitude:yourLongitude)
           mapVw.addAnnotation(pointAnnotation)
          
          }
          
          // MARK:- MapView Delegate
          
          
          func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?
          {
              if annotation is MKUserLocation
              {
                  return nil;
              }else{
                  let pinIdent = "Pin";
                  var pinView: MKAnnotationView?
                  if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: pinIdent)
                  {
                      dequeuedView.annotation = annotation;
                      pinView = dequeuedView;
                  }
                  else
                  {
                      pinView = MKAnnotationView(annotation: annotation, reuseIdentifier: pinIdent);
                      pinView?.image = UIImage(named: "yourImage")
          
                  }
          
          
                  return pinView;
              }
          }
          

          【讨论】:

          • 这是我见过的格式最差的代码
          猜你喜欢
          • 1970-01-01
          • 2020-10-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多