Swift-带有图像的自定义MKPointAnnotation [英] Swift - Custom MKPointAnnotation with Image

查看:121
本文介绍了Swift-带有图像的自定义MKPointAnnotation的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建自定义MKPointAnnotation以在地图视图上使用.看起来非常像Apple的照片中使用的照片:

I am trying to create a custom MKPointAnnotation to use on a map view. It looks very much like the one used in Apple's Photos:

我将从服务器上检索许多照片以及它们的位置.然后,我想显示一个上面的注释,其中的图像在注释内.

I will be retrieving a number of photos from a server, along with their location. I then want to display an annotation like the one above, with the image inside the annotation.

我目前有一个程序,可以在正确的坐标处添加普通的MKPointAnnotation,并且还可以从服务器中检索相关的照片.

I currently have a program that can add a normal MKPointAnnotation at the right coordinate, and can also retrieve the relevant photo from the server.

我想要做的就是将我的MKPointAnnotation设置为类似的样式.

All I want is to style my MKPointAnnotation to look just like that.

我尝试了其他答案,但是我认为这略有不同,因为我想每次都在模板上显示图像.

I have tried following other answers but I think this is slightly different because I want to show an image on a template every time.

推荐答案

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?是您需要覆盖的功能.

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? from MKMapViewDelegate is the function you need to override.

它允许您为每个注释提供自定义"视图.在此函数中,您可以使自定义视图(MKAnnotationView的子类)出队并设置自定义属性,也可以使具有属性image的常规MKAnnotationView出队.

It allows you to provide "custom" views for the each annotation. Within this function, you can either dequeue a custom view (subclass of MKAnnotationView) and set custom properties OR you can dequeue a regular MKAnnotationView which has a property image.

您可以设置该属性以显示自定义图像.无论如何,我还是希望使用自己的注释视图,因为您可以添加自定义布局(标签,imageViews等)和主题(颜色,图层等).

You can set that property to display custom images. I'd rather use my own annotationView anyway as you can add custom layouts (labels, imageViews, etc..) and themes (colours, layers, etc..).

示例:

//
//  ViewController.swift
//  Maps
//
//  Created by Brandon T on 2017-02-20.
//  Copyright © 2017 XIO. All rights reserved.
//

import UIKit
import MapKit


class ImageAnnotation : NSObject, MKAnnotation {
    var coordinate: CLLocationCoordinate2D
    var title: String?
    var subtitle: String?
    var image: UIImage?
    var colour: UIColor?

    override init() {
        self.coordinate = CLLocationCoordinate2D()
        self.title = nil
        self.subtitle = nil
        self.image = nil
        self.colour = UIColor.white
    }
}

class ImageAnnotationView: MKAnnotationView {
    private var imageView: UIImageView!

    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)

        self.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
        self.imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
        self.addSubview(self.imageView)

        self.imageView.layer.cornerRadius = 5.0
        self.imageView.layer.masksToBounds = true
    }

    override var image: UIImage? {
        get {
            return self.imageView.image
        }

        set {
            self.imageView.image = newValue
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class ViewController: UIViewController, MKMapViewDelegate {

    var mapView: MKMapView!
    var locationManager: CLLocationManager!

    override func viewDidLoad() {
        super.viewDidLoad()


        self.initControls()
        self.doLayout()
        self.loadAnnotations()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func initControls() {
        self.mapView = MKMapView()

        self.mapView.isRotateEnabled = true
        self.mapView.showsUserLocation = true
        self.mapView.delegate = self

        let center = CLLocationCoordinate2DMake(43.761539, -79.411079)
        let region = MKCoordinateRegionMake(center, MKCoordinateSpanMake(0.005, 0.005))
        self.mapView.setRegion(region, animated: true)
    }

    func doLayout() {
        self.view.addSubview(self.mapView)
        self.mapView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
        self.mapView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
        self.mapView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
        self.mapView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
        self.mapView.translatesAutoresizingMaskIntoConstraints = false
    }

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        if annotation.isKind(of: MKUserLocation.self) {  //Handle user location annotation..
            return nil  //Default is to let the system handle it.
        }

        if !annotation.isKind(of: ImageAnnotation.self) {  //Handle non-ImageAnnotations..
            var pinAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "DefaultPinView")
            if pinAnnotationView == nil {
                pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "DefaultPinView")
            }
            return pinAnnotationView
        }

        //Handle ImageAnnotations..
        var view: ImageAnnotationView? = mapView.dequeueReusableAnnotationView(withIdentifier: "imageAnnotation") as? ImageAnnotationView
        if view == nil {
            view = ImageAnnotationView(annotation: annotation, reuseIdentifier: "imageAnnotation")
        }

        let annotation = annotation as! ImageAnnotation
        view?.image = annotation.image
        view?.annotation = annotation

        return view
    }


    func loadAnnotations() {
        let request = NSMutableURLRequest(url: URL(string: "https://i.imgur.com/zIoAyCx.png")!)
        request.httpMethod = "GET"

        let session = URLSession(configuration: URLSessionConfiguration.default)
        let dataTask = session.dataTask(with: request as URLRequest) { (data, response, error) in
            if error == nil {

                let annotation = ImageAnnotation()
                annotation.coordinate = CLLocationCoordinate2DMake(43.761539, -79.411079)
                annotation.image = UIImage(data: data!, scale: UIScreen.main.scale)
                annotation.title = "Toronto"
                annotation.subtitle = "Yonge & Bloor"


                DispatchQueue.main.async {
                    self.mapView.addAnnotation(annotation)
                }
            }
        }

        dataTask.resume()
    }
}

这篇关于Swift-带有图像的自定义MKPointAnnotation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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