如何在 GMSMapView 前面添加一个按钮

How to add a button in front of a GMSMapView

我正在尝试在 GMSMapView 视图前添加一个按钮。 这是我的代码:

@IBOutlet weak var testButton: UIButton! 
@IBOutlet weak var mapView2: GMSMapView! 
override func viewDidLoad() {
    super.viewDidLoad()
    loadView()
}

那么这里是loadView()方法

override func loadView() {
    let camera = GMSCameraPosition.camera(withLatitude: 54.2785691, longitude: -8.4620978, zoom: 18.0)
    let mapView2 = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
    view = mapView2 
    mapView2.bringSubviewToFront(testButton)
}

这是我遇到的错误:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

如有任何帮助,我们将不胜感激!

你可以试试

class MyVc:UIViewController { 
  @IBOutlet weak var testButton: UIButton! 
  @IBOutlet weak var mapView2: GMSMapView! 
  override func viewDidLoad() {
    super.viewDidLoad()
    let camera = GMSCameraPosition.camera(withLatitude: 54.2785691, longitude: -8.4620978, zoom: 18.0)
    mapView2.animate(to: camera)
    view.bringSubviewToFront(testButton)
  }
}

我希望在 IBUI

View-> 
    -testButton
    -mapView2

顺便说一下,您可以将视图重新排列为

而不是 bringSubviewToFront
View-> 
    -mapView2
    -testButton

底部元素在前面

也不要为此类问题实施 loadView,因为它仅在您以编程方式创建 vc 或想要添加除 IB 之外的一些项目时才重要,在后一种情况下,您应该调用 super.loadView()