【问题标题】:How to add button on GMSMapView using swift 4如何使用 swift 4 在 GMSMapView 上添加按钮
【发布时间】:2018-07-23 21:09:33
【问题描述】:

这是我的视图控制器,即使我向 CGRect 添加值也无法正常工作

import UIKit
import GoogleMaps

class ViewController: UIViewController,CLLocationManagerDelegate, 
GMSMapViewDelegate {

 override func viewDidLoad() {
super.viewDidLoad()

let camera = GMSCameraPosition.camera(withLatitude: 52.649030, 
longitude: 1.174155, zoom: 14)
let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
mapView.delegate = self
self.view = mapView

let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: 52.649030, 
longitude: 1.174155)
marker.title = "marker1"
marker.snippet = "city"
marker.map = mapView
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
self.view.addSubview(button)

}

func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
 print(marker.position)
 return true
  }
  }

那么,我的代码中是否有任何错误? 谢谢

【问题讨论】:

  • CGRect 为空。试试看:UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
  • 对不起,我是新手,这是我的第一个问题,但仍然没有显示按钮
  • 添加文本或按钮背景颜色以在地图视图上查看按钮
  • 兄弟,您确实需要先查看在线教程,您似乎对iOS编程相当陌生。祝你好运!

标签: ios dictionary button swift4 google-maps-sdk-ios


【解决方案1】:

您的代码没有问题。按钮实际上在那里。 如果您检查图层,您可以在左上角看到它,如下所示:

只需添加按钮标题/标题颜色。或背景颜色,你会看到它。

    let button = UIButton(frame: CGRect(x: 50, y: 50, width: 100, height: 100))

button.setTitle("Button", for: .normal)
button.setTitleColor(.red, for: .normal)
button.addTarget(self, action: #selector(handleTap), for: .touchUpInside)
self.view.addSubview(button)

@objc func handleTap(_ sender: UIButton) {
    print("You tapped a button")
}

移动按钮并设置标题后,它会是这样的:

【讨论】:

  • 感谢您的帮助,我现在可以看到按钮了。还有一个问题,单击按钮时如何做某事(我如何处理此事件)?
  • 将目标添加到按钮 button.addTarget(self, action: #selector(handleTap), for: .touchUpInside) 并对其执行操作: func handleTap(_ sender: UIButton) { print("You点击了一个按钮") }
  • 这就是我想要的。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2015-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-16
  • 2019-10-06
  • 2021-03-28
  • 1970-01-01
相关资源
最近更新 更多