2

I am trying to get my own custom button floating over a GMSMapView. The button draws on the GMSMapView, but the button action is not triggered. The Floating button is written in SwiftUI and this is it:

struct MyLocationView: View {
    @ObservedObject var viewController: ViewController

    var body: some View {
        ZStack {
            Button(action: {
                print("Hello")
                self.viewController.myLocationButtonPressed = !self.viewController.myLocationButtonPressed
            }) {
                ZStack {
                    Circle()
                        .foregroundColor(.black)
                        .frame(width: 60, height: 60)
                        .shadow(radius: 10)
                    Image(systemName: viewController.myLocationButtonPressed ? "location.fill" : "location")
                        .foregroundColor(.blue)
                }
            }
        }
    }
}

This is my viewController

import UIKit
import SwiftUI
import GoogleMaps

class ViewController: UIViewController, ObservableObject {
    @Published var myLocationButtonPressed: Bool = false
    @IBOutlet var mapView: GMSMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // My Location Button
        let myLocationView = MyLocationView(viewController: self)
        let hostingController = UIHostingController(rootView: myLocationView)
        hostingController.view.backgroundColor = .blue
        addChild(hostingController)
        hostingController.view.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(hostingController.view)
        hostingController.didMove(toParent: self)

        NSLayoutConstraint.activate([
            hostingController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            hostingController.view.topAnchor.constraint(equalTo: view.topAnchor),
            hostingController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            hostingController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ])
    }
}

Any idea why the button action is not working here?

Arthur Garza
  • 2,031
  • 2
  • 14
  • 17
  • I have a similar problem. Did you find a solution? – Dogahe Sep 11 '20 at 02:09
  • Unfortunately not. I ended up creating my custom button in UIKit. :/ What problem are you having? – Arthur Garza Sep 11 '20 at 19:49
  • I had a problem that is resolved ever since I contacted you here. For me it was the size of the button and by just adding a padding() it was resolved: https://stackoverflow.com/questions/63840027/swiftui-button-on-top-of-a-mkmapview-does-not-get-triggered – Dogahe Sep 11 '20 at 20:52

0 Answers0