热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

将标注/语音气泡添加到MapView的用户注释中

如何解决《将标注/语音气泡添加到MapView的用户注释中》经验,为你挑选了1个好方法。

现在,我的应用程序显示一个customUserAnnotationView,其中包含用户批注的自定义图像(您可以在ViewController.swift中看到它)。我还创建了一个自定义UIView,希望将其用作用户注释上方的注释(其代码和图像位于SpeechBubble.swift下)。

我想结合这两个对象,以便可以显示CustomUserAnnotationView和上面的注释中放置的Custom UIView(SpeechBubble.swift)。

我尝试从 多个 mapbox 教程制作Frankenstein程序的尝试对我来说还没有成功。我只想将我创建的自定义注释类放在图像上方,并可能添加一个小三角形以使其看起来像气泡。


ViewController.swift

import Mapbox

class ViewController: UIViewController, MGLMapViewDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()
        let mapView = MGLMapView(frame: view.bounds)
        mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        mapView.delegate = self

        // Enable heading tracking mode so that the arrow will appear.
        mapView.userTrackingMode = .followWithHeading

        // Enable the permanent heading indicator, which will appear when the tracking mode is not `.followWithHeading`.
        mapView.showsUserHeadingIndicator = true

        view.addSubview(mapView)

        let idea =  UITextView(frame: CGRect(x: 0, y: 0, width: 100, height: 40))
        idea.text = "Hello There"
        idea.textAlignment = NSTextAlignment.center

        let sb = SpeechBubble(coord: mapView.targetCoordinate, idea: idea)
        mapView.addSubview(sb)
    }

    func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
        return true
    }

    func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
        // Substitute our custom view for the user location annotation. This custom view is defined below.
        if annotation is MGLUserLocation && mapView.userLocation != nil {
            return Avatar()
        }
        return nil
    }

    // Optional: tap the user location annotation to toggle heading tracking mode.
    func mapView(_ mapView: MGLMapView, didSelect annotation: MGLAnnotation) {
        if mapView.userTrackingMode != .followWithHeading {
            mapView.userTrackingMode = .followWithHeading
        } else {
            mapView.resetNorth()
        }

        // We're borrowing this method as a gesture recognizer, so reset selection state.
        mapView.deselectAnnotation(annotation, animated: false)
    }
}


SpeechBubble.swift

import UIKit
import Mapbox

class SpeechBubble: UIView, MGLMapViewDelegate{

    //var sbView: UIView

    init(coord: CLLocationCoordinate2D, idea: UITextView) {

        let width = CGFloat(180)
        let height = UITextField.layoutFittingExpandedSize.height + 32
        super.init(frame: CGRect(x: CGFloat(coord.latitude), y: CGFloat(coord.longitude), width: width, height: height))

        self.addSubview(idea)
        self.addSubview(buttonsView());
        self.addSubview(upvoteView());
    }

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

    func upvoteView() -> UIView {
        let uView = UIView()

        let vCnt = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
        vCnt.center = CGPoint(x: 10.5, y: 32)
        vCnt.textAlignment = .center
        vCnt.text = "0"

        let uButton  = UIButton(type: .custom)
        uButton.frame = CGRect(x: vCnt.frame.size.width + 5, y: 0, width: 32, height: 32);
        let uImage = UIImage (named: "Upvote")
        uButton.setImage(uImage, for: .normal)

        uView.frame.size.width = vCnt.frame.size.width + uButton.frame.size.width + 5
        uView.frame.size.height = max(vCnt.frame.size.height, uButton.frame.size.height)

        uView.frame = CGRect(
            x: 0,
            y: self.frame.size.height - uView.frame.size.height,
            width: uView.frame.size.width,
            height: uView.frame.size.height );
        uView.addSubview(vCnt)
        uView.addSubview(uButton)
        return uView
    }

    func buttonsView() -> UIView {
        let bView = UIView()

        let jButton  = UIButton(type: .custom)
        rButton.frame = CGRect(x: 0, y: 0, width: 35, height: 32);
        let rImage = UIImage (named: "Rocket")
        rButton.setImage(rImage, for: .normal)

        let pButton  = UIButton(type: .custom)
        pButton.frame = CGRect(x: jButton.frame.size.width + 5, y: 0, width: 31, height: 36);
        let pImage = UIImage (named: "Profile")
        pButton.setImage(pImage, for: .normal)

        bView.frame.size.width = rButton.frame.size.width + pButton.frame.size.width + 5
        bView.frame.size.height = max(rButton.frame.size.height, pButton.frame.size.height)

        bView.frame = CGRect(
            x: self.frame.size.width - bView.frame.size.width,
            y: self.frame.size.height - bView.frame.size.height,
            width: bView.frame.size.width,
            height: bView.frame.size.height );
        bView.addSubview(rButton)
        bView.addSubview(pButton)
        return bView
    }

}


头像迅捷

import Mapbox

class Avatar: MGLUserLocationAnnotationView {
    let size: CGFloat = 48
    var arrow: CALayer!
    //var arrow: CAShapeLayer!

    // -update is a method inherited from MGLUserLocationAnnotationView. It updates the appearance of the user location annotation when needed. This can be called many times a second, so be careful to keep it lightweight.
    override func update() {
        if frame.isNull {
            frame = CGRect(x: 0, y: 0, width: size, height: size)
            return setNeedsLayout()
        }

        // Check whether we have the user’s location yet.
        if CLLocationCoordinate2DIsValid(userLocation!.coordinate) {
            setupLayers()
            updateHeading()
        }
    }

    private func updateHeading() {
        // Show the heading arrow, if the heading of the user is available.
        if let heading = userLocation!.heading?.trueHeading {
            arrow.isHidden = false

            // Get the difference between the map’s current direction and the user’s heading, then convert it from degrees to radians.
            let rotation: CGFloat = -MGLRadiansFromDegrees(mapView!.direction - heading)

            // If the difference would be perceptible, rotate the arrow.
            if abs(rotation) > 0.01 {
                // Disable implicit animations of this rotation, which reduces lag between changes.
                CATransaction.begin()
                CATransaction.setDisableActions(true)
                arrow.setAffineTransform(CGAffineTransform.identity.rotated(by: rotation))
                CATransaction.commit()
            }
        } else {
            arrow.isHidden = true
        }
    }

    private func setupLayers() {
        // This dot forms the base of the annotation.
        if arrow == nil {
            arrow = CALayer()
            let myImage = UIImage(named: "will_smith")?.cgImage
            arrow.bounds = CGRect(x: 0, y: 0, width: size, height: size)
            arrow.cOntents= myImage
            layer.addSublayer(arrow)
        }

    }

    // Calculate the vector path for an arrow, for use in a shape layer.
    private func arrowPath() -> CGPath {
        let max: CGFloat = size / 2
        let pad: CGFloat = 3

        let top =    CGPoint(x: max * 0.5, y: 0)
        let left =   CGPoint(x: 0 + pad,   y: max - pad)
        let right =  CGPoint(x: max - pad, y: max - pad)
        let center = CGPoint(x: max * 0.5, y: max * 0.6)

        let bezierPath = UIBezierPath()
        bezierPath.move(to: top)
        bezierPath.addLine(to: left)
        bezierPath.addLine(to: center)
        bezierPath.addLine(to: right)
        bezierPath.addLine(to: top)
        bezierPath.close()

        return bezierPath.cgPath
    }
}

-------------------------------------------------- -------------------------------------------------- ----




更新 我试图创建Answer和我的代码的科学怪人程序,并Property 'self.representedObject' not initialized at super.init call在SpeechBubble.swift中收到以下错误。我还将所有旧代码从SpeechBubble.swift移入insideSpeechBubble.swift

更新了SpeechBubble.swift

    import UIKit
    import Mapbox

    class SpeechBubble: UIView, MGLCalloutView {

        // Your IBOutlets //

        var representedObject: MGLAnnotation
        var annotationPoint: CGPoint
        // Required views but unused for this implementation.
        lazy var leftAccessoryView = UIView()
        lazy var rightAccessoryView = UIView()
        var contentView: MGLMapView
        weak var delegate: MGLCalloutViewDelegate?

        // MARK: - init methods

        required init(annotation: MGLAnnotation, frame: CGRect, annotationPoint: CGPoint) {
            let idea =  UITextView(frame: CGRect(x: 0, y: 0, width: 100, height: 40))
            idea.text = "Hello There"
            idea.textAlignment = NSTextAlignment.center
            self.representedObject = annotation
            self.annotatiOnPoint= annotationPoint
            cOntentView= InsideSpeechBubble(coord: annotationPoint, idea: idea )
            super.init(frame: frame)
            commonInit()
        }

        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            commonInit()
        }

        private func commonInit() {
            Bundle.main.loadNibNamed("SpeechBubble", owner: self, options: nil)
            addSubview(contentView as UIView)
            contentView.frame = self.bounds

            // Do your initialisation //
        }

        // MARK: - MGLCalloutView methods

        func presentCallout(from rect: CGRect, in view: UIView, constrainedTo constrainedRect: CGRect, animated: Bool) {
            // Present the custom callout slightly above the annotation's view. Initially invisble.
            self.center = annotationPoint.applying(CGAffineTransform(translationX: 0, y: -self.frame.height - 20.0))

            // I have logic here for setting the correct image and button states //
        }

        func dismissCallout(animated: Bool) {
            removeFromSuperview()
    }
}

更新了ViewController.swift

import Mapbox


class ViewController: UIViewController, MGLMapViewDelegate {
    //let point = MGLPointAnnotation()

    override func viewDidLoad() {
        super.viewDidLoad()
        let mapView = MGLMapView(frame: view.bounds)
        mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        mapView.delegate = self

        // Enable heading tracking mode so that the arrow will appear.
        mapView.userTrackingMode = .followWithHeading

        // Enable the permanent heading indicator, which will appear when the tracking mode is not `.followWithHeading`.
        mapView.showsUserHeadingIndicator = true

        view.addSubview(mapView)

        let HighDea =  UITextView(frame: CGRect(x: 0, y: 0, width: 100, height: 40))
        HighDea.text = "Hello There"
        HighDea.textAlignment = NSTextAlignment.center

        //let sb = SpeechBubble()
        //mapView.addSubview(sb)
    }

    func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
        return true
    }

    func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
        // Substitute our custom view for the user location annotation. This custom view is defined below.
        if annotation is MGLUserLocation && mapView.userLocation != nil {
            return Avatar()
        }
        return nil
    }

    func mapView(_ mapView: MGLMapView, calloutViewFor annotation: MGLAnnotation) -> MGLCalloutView? {
        // Do your annotation-specific preparation here //

        // I get the correct size from my xib file.
        let viewFrame = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 261.0, height: 168.0))
        // Get the annotation's location in the view's coordinate system.
        let annotatiOnPoint= mapView.convert(annotation.coordinate, toPointTo: nil)

        let customCalloutView = SpeechBubble(annotation: annotation, frame: viewFrame, annotationPoint: annotationPoint)

        return customCalloutView
    }

//    func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
        // This example is only concerned with point annotations.
//        guard annotation is MGLPointAnnotation else {
//            return nil
//        }

        // Use the point annotation’s longitude value (as a string) as the reuse identifier for its view.
//        let reuseIdentifier = "\(annotation.coordinate.longitude)"

        // For better performance, always try to reuse existing annotations.
//        var annotatiOnView= mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier)

        // If there’s no reusable annotation view available, initialize a new one.
//        if annotatiOnView== nil {
//            annotatiOnView= CustomAnnotationView(reuseIdentifier: reuseIdentifier)
//            annotationView!.bounds = CGRect(x: 0, y: 0, width: 40, height: 40)

            // Set the annotation view’s background color to a value determined by its longitude.
  //          let hue = CGFloat(annotation.coordinate.longitude) / 100
  //          annotationView!.backgroundColor = UIColor(hue: hue, saturation: 0.5, brightness: 1, alpha: 1)
  //      }

  //      return annotationView
  //  }

    // Optional: tap the user location annotation to toggle heading tracking mode.
    func mapView(_ mapView: MGLMapView, didSelect annotation: MGLAnnotation) {
        if mapView.userTrackingMode != .followWithHeading {
            mapView.userTrackingMode = .followWithHeading
        } else {
            mapView.resetNorth()
        }

        // We're borrowing this method as a gesture recognizer, so reset selection state.
        mapView.deselectAnnotation(annotation, animated: false)
    }
}

Magnas.. 5

当我为Mapbox注释实现自定义标注时,我使用了xib文件来设计实际的标注。我发现,与尝试从代码中构造UI相比,它给我提供了更多的即时反馈(但显然可以随您的喜好进行操作)。

这给了我类似以下内容。

使用UIImage作为背景,可以实现我选择的任何形状。在这里,我使用白色周围的透明度为您提供问题中提到的圆形元素和底部三角形。

此UIView的Swift文件(您的SpeechBubble)需要符合MGLCalloutView协议,而不是MGLMapViewDelegate您当前所拥有的。您ViewControllerMGLMapViewDelegate,而不是您的自定义标注。在IB中的Identity Inspector中以通常的方式将xib文件和Swift文件配对。所以会是这样的:

    import UIKit
    import Mapbox

    class SpeechBubble: UIView, MGLCalloutView {

    // Your IBOutlets //
    @IBOutlet var contentView: UIView! // The custom callout's view.

    var representedObject: MGLAnnotation
    var annotationPoint: CGPoint
    // Required views but unused for this implementation.
    lazy var leftAccessoryView = UIView()
    lazy var rightAccessoryView = UIView()

    weak var delegate: MGLCalloutViewDelegate?

    // MARK: - init methods

    required init(annotation: YourAnnotation, frame: CGRect, annotationPoint: CGPoint) {
        self.representedObject = annotation
        self.annotatiOnPoint= annotationPoint

        super.init(frame: frame)

        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        commonInit()
    }

    private func commonInit() {
        Bundle.main.loadNibNamed("SpeechBubble", owner: self, options: nil)
        addSubview(contentView)
        contentView.frame = self.bounds

        // Do your initialisation //
    }

    // MARK: - MGLCalloutView methods

    func presentCallout(from rect: CGRect, in view: UIView, constrainedTo constrainedRect: CGRect, animated: Bool) {
        // Present the custom callout slightly above the annotation's view. Initially invisble.
        self.center = annotationPoint.applying(CGAffineTransform(translationX: 0, y: -self.frame.height - 20.0))

        // I have logic here for setting the correct image and button states //
    }

    func dismissCallout(animated: Bool) {
        removeFromSuperview()
    }

然后,您似乎只是缺少了在请求时MGLMapViewDelegate实际返回SpeechBubble视图的方法。它应该在您的ViewController文件中。

    func mapView(_ mapView: MGLMapView, calloutViewFor annotation: MGLAnnotation) -> MGLCalloutView? {
        // Do your annotation-specific preparation here //

        // I get the correct size from my xib file.
        let viewFrame = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 261.0, height: 168.0))
        // Get the annotation's location in the view's coordinate system.
        let annotatiOnPoint= mapView.convert(annotation.coordinate, toPointTo: nil)
        let customCalloutView = SpeechBubble(annotation: YourAnnotation, frame: viewFrame, annotationPoint: annotationPoint)

        return customCalloutView
    }

希望这将使您更接近实现自己的目标。顺便说一句,这个问题的版本比第一个要领先几英里。

编辑+++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++

在没有看到您的项目的情况下几乎不可能完成这项工作,因此我整理了一个基本的实现。它基于此处的Mapbox示例:Mapbox自定义标注,由于某种原因,它没有显示如何实际提供标注视图。我还扩展了它以允许自定义注释图像。如果可以进行此工作,则应该能够将相关部分移至您自己的项目中。

我强烈建议您,如果尝试实施以下内容,请在一个新项目中进行。

视图控制器。

    import Mapbox

    class ViewController: UIViewController, MGLMapViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        let mapView = MGLMapView(frame: view.bounds, styleURL: MGLStyle.lightStyleURL)
        mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        mapView.tintColor = .darkGray
        view.addSubview(mapView)

        // Set the map view‘s delegate property.
        mapView.delegate = self

        // Initialize and add the marker annotation.
        let coordinate = CLLocationCoordinate2D(latitude: 0, longitude: 0)
        let marker = MyAnnotation(coordinate: coordinate, title: "Bingo", subtitle: "Bongo")

        // Add marker to the map.
        mapView.addAnnotation(marker)
    }

    func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
        return true
    }

    func mapView(_ mapView: MGLMapView, calloutViewFor annotation: MGLAnnotation) -> MGLCalloutView? {
        // Instantiate and return our custom callout view.
        let annotatiOnPoint= mapView.convert(annotation.coordinate, toPointTo: nil)
        let viewFrame = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 250.0, height: 178.0))
        return CustomCalloutView(representedObject: annotation, frame: viewFrame, annotationPoint: annotationPoint)
    }

    func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
        if let annotatiOnView= mapView.dequeueReusableAnnotationView(withIdentifier: "myAnnotationView") {
            return annotationView
        } else {
            let annotatiOnView= MyAnnotationView(reuseIdentifier: "myAnnotationView", size: CGSize(width: 45, height: 45), annotation: annotation)
            return annotationView
        }
    }

    func mapView(_ mapView: MGLMapView, tapOnCalloutFor annotation: MGLAnnotation) {
        // Optionally handle taps on the callout.
        print("Tapped the callout for: \(annotation)")

        // Hide the callout.
        mapView.deselectAnnotation(annotation, animated: true)
    }
}

CustomCalloutView.swift

import UIKit
import Mapbox

class CustomCalloutView: UIView, MGLCalloutView {

@IBOutlet var contentView: UIView!

weak var delegate: MGLCalloutViewDelegate?

var representedObject: MGLAnnotation
var annotationPoint: CGPoint
// Required views but unused for this implementation.
lazy var leftAccessoryView = UIView()
lazy var rightAccessoryView = UIView()

required init(representedObject: MGLAnnotation, frame: CGRect, annotationPoint: CGPoint) {
    self.representedObject = representedObject
    self.annotatiOnPoint= annotationPoint

    super.init(frame: frame)

    commonInit()
}

required init?(coder aDecoder: NSCoder) {
    let coordinate = CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0)
    self.representedObject = MyAnnotation(coordinate: coordinate, title: "", subtitle: "")
    self.annotatiOnPoint= CGPoint(x: 50.0, y: 50.0)

    super.init(coder: aDecoder)

    commonInit()
}

func commonInit() {
    Bundle.main.loadNibNamed("CustomCalloutView", owner: self, options: nil)
    addSubview(contentView)
}

func presentCallout(from rect: CGRect, in view: UIView, constrainedTo constrainedRect: CGRect, animated: Bool) {
    // Present the custom callout slightly above the annotation's view. Initially invisble.
    self.center = annotationPoint.applying(CGAffineTransform(translationX: 0.0, y: -120.0))

    view.addSubview(self)
}

func dismissCallout(animated: Bool) {
    removeFromSuperview()
}

}

这与xib文件相关联/标识。现在它只包含一个简单的图像形状。我不得不(重新)引入contentView IBOutlet,因为我无法从Bundle中加载内容并将其添加到commonInit()中的self上使一切变得很愉快。

自定义注释类。

    import UIKit
    import Mapbox

    // MGLAnnotation protocol reimplementation
    class MyAnnotation: NSObject, MGLAnnotation {

    // As a reimplementation of the MGLAnnotation protocol, we have to add mutable coordinate and (sub)title properties ourselves.
    var coordinate: CLLocationCoordinate2D
    var title: String?
    var subtitle: String?

    // Custom properties that we will use to customize the annotation.
    var image: UIImage?
    var reuseIdentifier: String?

    init(coordinate: CLLocationCoordinate2D, title: String?, subtitle: String?) {
        self.coordinate = coordinate
        self.title = title
        self.subtitle = subtitle

        self.reuseIdentifier = "myAnnotation"
    }
}

MGLAnnotationView子类。

    import UIKit
    import Mapbox

    class MyAnnotationView: MGLAnnotationView {

    init(reuseIdentifier: String, size: CGSize, annotation: MGLAnnotation) {
        super.init(reuseIdentifier: reuseIdentifier)

        // This property prevents the annotation from changing size when the map is tilted.
        scalesWithViewingDistance = false

        // Begin setting up the view.
        frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)

        let imageView = UIImageView(frame: frame)
        var image = UIImage()
        if annotation is MyAnnotation {
            image = UIImage(named: "frog")!
        }

        imageView.image = image
        addSubview(imageView)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

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

自然地,有很多硬编码的数字,并且需要一个名为frog的图像,但是您可以更改所有这些图像并根据需要对其进行改进。需要在身份检查器等中以通常的方式链接CustomCalloutView.swift和CustomCalloutView.xib。



1> Magnas..:

当我为Mapbox注释实现自定义标注时,我使用了xib文件来设计实际的标注。我发现,与尝试从代码中构造UI相比,它给我提供了更多的即时反馈(但显然可以随您的喜好进行操作)。

这给了我类似以下内容。

使用UIImage作为背景,可以实现我选择的任何形状。在这里,我使用白色周围的透明度为您提供问题中提到的圆形元素和底部三角形。

此UIView的Swift文件(您的SpeechBubble)需要符合MGLCalloutView协议,而不是MGLMapViewDelegate您当前所拥有的。您ViewControllerMGLMapViewDelegate,而不是您的自定义标注。在IB中的Identity Inspector中以通常的方式将xib文件和Swift文件配对。所以会是这样的:

    import UIKit
    import Mapbox

    class SpeechBubble: UIView, MGLCalloutView {

    // Your IBOutlets //
    @IBOutlet var contentView: UIView! // The custom callout's view.

    var representedObject: MGLAnnotation
    var annotationPoint: CGPoint
    // Required views but unused for this implementation.
    lazy var leftAccessoryView = UIView()
    lazy var rightAccessoryView = UIView()

    weak var delegate: MGLCalloutViewDelegate?

    // MARK: - init methods

    required init(annotation: YourAnnotation, frame: CGRect, annotationPoint: CGPoint) {
        self.representedObject = annotation
        self.annotatiOnPoint= annotationPoint

        super.init(frame: frame)

        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        commonInit()
    }

    private func commonInit() {
        Bundle.main.loadNibNamed("SpeechBubble", owner: self, options: nil)
        addSubview(contentView)
        contentView.frame = self.bounds

        // Do your initialisation //
    }

    // MARK: - MGLCalloutView methods

    func presentCallout(from rect: CGRect, in view: UIView, constrainedTo constrainedRect: CGRect, animated: Bool) {
        // Present the custom callout slightly above the annotation's view. Initially invisble.
        self.center = annotationPoint.applying(CGAffineTransform(translationX: 0, y: -self.frame.height - 20.0))

        // I have logic here for setting the correct image and button states //
    }

    func dismissCallout(animated: Bool) {
        removeFromSuperview()
    }

然后,您似乎只是缺少了在请求时MGLMapViewDelegate实际返回SpeechBubble视图的方法。它应该在您的ViewController文件中。

    func mapView(_ mapView: MGLMapView, calloutViewFor annotation: MGLAnnotation) -> MGLCalloutView? {
        // Do your annotation-specific preparation here //

        // I get the correct size from my xib file.
        let viewFrame = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 261.0, height: 168.0))
        // Get the annotation's location in the view's coordinate system.
        let annotatiOnPoint= mapView.convert(annotation.coordinate, toPointTo: nil)
        let customCalloutView = SpeechBubble(annotation: YourAnnotation, frame: viewFrame, annotationPoint: annotationPoint)

        return customCalloutView
    }

希望这将使您更接近实现自己的目标。顺便说一句,这个问题的版本比第一个要领先几英里。

编辑+++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++

在没有看到您的项目的情况下几乎不可能完成这项工作,因此我整理了一个基本的实现。它基于此处的Mapbox示例:Mapbox自定义标注,由于某种原因,它没有显示如何实际提供标注视图。我还扩展了它以允许自定义注释图像。如果可以进行此工作,则应该能够将相关部分移至您自己的项目中。

我强烈建议您,如果尝试实施以下内容,请在一个新项目中进行。

视图控制器。

    import Mapbox

    class ViewController: UIViewController, MGLMapViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        let mapView = MGLMapView(frame: view.bounds, styleURL: MGLStyle.lightStyleURL)
        mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        mapView.tintColor = .darkGray
        view.addSubview(mapView)

        // Set the map view‘s delegate property.
        mapView.delegate = self

        // Initialize and add the marker annotation.
        let coordinate = CLLocationCoordinate2D(latitude: 0, longitude: 0)
        let marker = MyAnnotation(coordinate: coordinate, title: "Bingo", subtitle: "Bongo")

        // Add marker to the map.
        mapView.addAnnotation(marker)
    }

    func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
        return true
    }

    func mapView(_ mapView: MGLMapView, calloutViewFor annotation: MGLAnnotation) -> MGLCalloutView? {
        // Instantiate and return our custom callout view.
        let annotatiOnPoint= mapView.convert(annotation.coordinate, toPointTo: nil)
        let viewFrame = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 250.0, height: 178.0))
        return CustomCalloutView(representedObject: annotation, frame: viewFrame, annotationPoint: annotationPoint)
    }

    func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
        if let annotatiOnView= mapView.dequeueReusableAnnotationView(withIdentifier: "myAnnotationView") {
            return annotationView
        } else {
            let annotatiOnView= MyAnnotationView(reuseIdentifier: "myAnnotationView", size: CGSize(width: 45, height: 45), annotation: annotation)
            return annotationView
        }
    }

    func mapView(_ mapView: MGLMapView, tapOnCalloutFor annotation: MGLAnnotation) {
        // Optionally handle taps on the callout.
        print("Tapped the callout for: \(annotation)")

        // Hide the callout.
        mapView.deselectAnnotation(annotation, animated: true)
    }
}

CustomCalloutView.swift

import UIKit
import Mapbox

class CustomCalloutView: UIView, MGLCalloutView {

@IBOutlet var contentView: UIView!

weak var delegate: MGLCalloutViewDelegate?

var representedObject: MGLAnnotation
var annotationPoint: CGPoint
// Required views but unused for this implementation.
lazy var leftAccessoryView = UIView()
lazy var rightAccessoryView = UIView()

required init(representedObject: MGLAnnotation, frame: CGRect, annotationPoint: CGPoint) {
    self.representedObject = representedObject
    self.annotatiOnPoint= annotationPoint

    super.init(frame: frame)

    commonInit()
}

required init?(coder aDecoder: NSCoder) {
    let coordinate = CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0)
    self.representedObject = MyAnnotation(coordinate: coordinate, title: "", subtitle: "")
    self.annotatiOnPoint= CGPoint(x: 50.0, y: 50.0)

    super.init(coder: aDecoder)

    commonInit()
}

func commonInit() {
    Bundle.main.loadNibNamed("CustomCalloutView", owner: self, options: nil)
    addSubview(contentView)
}

func presentCallout(from rect: CGRect, in view: UIView, constrainedTo constrainedRect: CGRect, animated: Bool) {
    // Present the custom callout slightly above the annotation's view. Initially invisble.
    self.center = annotationPoint.applying(CGAffineTransform(translationX: 0.0, y: -120.0))

    view.addSubview(self)
}

func dismissCallout(animated: Bool) {
    removeFromSuperview()
}

}

这与xib文件相关联/标识。现在它只包含一个简单的图像形状。我不得不(重新)引入contentView IBOutlet,因为我无法从Bundle中加载内容并将其添加到commonInit()中的self上使一切变得很愉快。

自定义注释类。

    import UIKit
    import Mapbox

    // MGLAnnotation protocol reimplementation
    class MyAnnotation: NSObject, MGLAnnotation {

    // As a reimplementation of the MGLAnnotation protocol, we have to add mutable coordinate and (sub)title properties ourselves.
    var coordinate: CLLocationCoordinate2D
    var title: String?
    var subtitle: String?

    // Custom properties that we will use to customize the annotation.
    var image: UIImage?
    var reuseIdentifier: String?

    init(coordinate: CLLocationCoordinate2D, title: String?, subtitle: String?) {
        self.coordinate = coordinate
        self.title = title
        self.subtitle = subtitle

        self.reuseIdentifier = "myAnnotation"
    }
}

MGLAnnotationView子类。

    import UIKit
    import Mapbox

    class MyAnnotationView: MGLAnnotationView {

    init(reuseIdentifier: String, size: CGSize, annotation: MGLAnnotation) {
        super.init(reuseIdentifier: reuseIdentifier)

        // This property prevents the annotation from changing size when the map is tilted.
        scalesWithViewingDistance = false

        // Begin setting up the view.
        frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)

        let imageView = UIImageView(frame: frame)
        var image = UIImage()
        if annotation is MyAnnotation {
            image = UIImage(named: "frog")!
        }

        imageView.image = image
        addSubview(imageView)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

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

自然地,有很多硬编码的数字,并且需要一个名为frog的图像,但是您可以更改所有这些图像并根据需要对其进行改进。需要在身份检查器等中以通常的方式链接CustomCalloutView.swift和CustomCalloutView.xib。


推荐阅读
  • iOS如何实现手势
    这篇文章主要为大家展示了“iOS如何实现手势”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“iOS ... [详细]
  • 使用 ModelAttribute 实现页面数据自动填充
    本文介绍了如何利用 Spring MVC 中的 ModelAttribute 注解,在页面跳转后自动填充表单数据。主要探讨了两种实现方法及其背后的原理。 ... [详细]
  • 本文探讨了如何使用Scrapy框架构建高效的数据采集系统,以及如何通过异步处理技术提升数据存储的效率。同时,文章还介绍了针对不同网站采用的不同采集策略。 ... [详细]
  • 导读:本文来自SwiftGG翻译组,作者@walkingway基于苹果Swift官方博客中TedKremenek所撰写的“Swift2.2Released!”文章进行了关于Swift2. ... [详细]
  • 本文提供了一个SQL脚本,用于在Microsoft SQL Server中创建一个数据字典视图,该视图详细列出了表名、表描述、字段名称、字段描述、字段类型、字段大小、字段精度、是否可为空、默认值以及是否为标识或主键等信息。 ... [详细]
  • 浅谈Android五大布局——LinearLayout、FrameLayout和AbsoulteLa
    为什么80%的码农都做不了架构师?Android的界面是有布局和组件协同完成的,布局好比是建筑里的框架,而组件则相当于建筑里的砖瓦。 ... [详细]
  • java datarow_DataSet  DataTable DataRow 深入浅出
    本篇文章适合有一定的基础的人去查看,最好学习过一定net编程基础在来查看此文章。1.概念DataSet是ADO.NET的中心概念。可以把DataSet当成内存中的数据 ... [详细]
  • Android 开发技巧:使用 AsyncTask 实现后台任务与 UI 交互
    本文详细介绍了如何在 Android 应用中利用 AsyncTask 来执行后台任务,并及时将任务进展反馈给用户界面,提高用户体验。 ... [详细]
  • 本文探讨了如何利用 Android 的 Movie 类来展示 GIF 动画,并详细介绍了调整 GIF 尺寸以适应不同布局的方法。同时,提供了相关的代码示例和注意事项。 ... [详细]
  • 当前,众多初创企业对全栈工程师的需求日益增长,但市场中却存在大量所谓的“伪全栈工程师”,尤其是那些仅掌握了Node.js技能的前端开发人员。本文旨在深入探讨全栈工程师在现代技术生态中的真实角色与价值,澄清对这一角色的误解,并强调真正的全栈工程师应具备全面的技术栈和综合解决问题的能力。 ... [详细]
  • 在Swift编程中,派生类中重写方法时调用其父类的同名方法是一种常见的做法。然而,如果不正确地处理这种调用,可能会导致程序崩溃。本文详细分析了这一问题的根源,并提供了有效的解决策略,帮助开发者避免此类错误。例如,在一个自定义的`ViewController`类中继承自`UITableViewController`时,如果重写了某个方法而未恰当调用父类的实现,就可能引发运行时异常。通过本文的指导,读者将能够更好地理解Swift中的方法重载机制,确保代码的稳定性和安全性。 ... [详细]
  • 在Swift 3中,默认情况下不自动关闭转义闭包的原因是为了避免潜在的内存管理和生命周期问题。明确使用“self”则是为了提高代码的可读性和安全性,确保开发者清楚地意识到闭包捕获了外部变量,从而避免意外的引用循环和资源泄漏。 ... [详细]
  • Struts2进阶指南:实现自定义拦截器详解
    在Struts2框架中,自定义拦截器的运用至关重要。通过定义拦截器或拦截器栈,可以灵活地扩展和控制应用程序的行为。本文将详细介绍如何创建和配置自定义拦截器,以实现更高效的功能管理和维护。 ... [详细]
  • [译]  OS X 和 iOS 的测绘框架Core Plot 入门教程
    [译] OS X 和 iOS 的测绘框架Core Plot 入门教程 ... [详细]
  • 我正在尝试使SwiftUI中的按钮在文本旁边显示图像。但是,即使不在按钮中时图像 ... [详细]
author-avatar
sprite_77
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有