swift - 以编程方式更改 Google map 大小 (Swift)

标签 swift google-maps gmsmapview

我正在尝试以编程方式添加 Google GMSMapView,但遇到了困难,希望得到任何帮助。我想将 map 的约束设置为 View 的边缘。

但是,当我这样做时,我收到错误:“无法使用 anchor 激活约束,因为它们没有共同的祖先。约束或其 anchor 是否引用不同 View 层次结构中的项目?”

var mapView:GMSMapView?

override func viewDidLoad() {
    super.viewDidLoad()

    mapView = GMSMapView.map(withFrame: CGRect(x: 100, y: 100, width: 200, height: 200), camera: GMSCameraPosition.camera(withLatitude: 51.050657, longitude: 10.649514, zoom: 5.5))

    mapView?.center = self.view.center

    mapView?.topAnchor.constraint(equalTo: view.topAnchor).isActive=true
    mapView?.leftAnchor.constraint(equalTo: view.leftAnchor).isActive=true
    mapView?.rightAnchor.constraint(equalTo: view.rightAnchor).isActive=true
    mapView?.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 60).isActive=true

    self.view.addSubview(mapView!)

}

如果省略 anchor ,我可以让 Google map 正确加载,所以我相信我已经正确设置了它。我只是不明白如何正确设置 anchor 的概念。

This solution类似,但更侧重于添加具有自动布局的 View 。

最佳答案

当您在将 View 添加到父 View 之前对其应用约束时,就会出现此问题。还将translatesAutoresizingMaskIntoConstraints 设置为 false 以使约束起作用。

self.view.addSubview(mapView!)
mapView?.translatesAutoresizingMaskIntoConstraints = false
mapView?.topAnchor.constraint(equalTo: view.topAnchor).isActive=true
mapView?.leftAnchor.constraint(equalTo: view.leftAnchor).isActive=true
mapView?.rightAnchor.constraint(equalTo: view.rightAnchor).isActive=true
mapView?.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 60).isActive=true

关于swift - 以编程方式更改 Google map 大小 (Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52324028/

相关文章:

ios - 谷歌地图模糊使用 GMSMapView 类型

ios - 如何使用 Swift 播放 mp3 url?

swift - RealityKit 和 ARKit – 当应用程序启动时,AR 项目在寻找什么?

mysql - 搜索点周围的距离(使用 MBR 包含)

jquery - 在 Bootstrap Carousel 中嵌入 Google map

ios - 如何在单击按钮时快速将Google Map的主题从夜间模式更改为标准模式

ios - 检测点击何时在 UITextView 之外

ios - 并行多个快速动画不起作用

jquery - Bootstrap 困境。调整 Google map 大小

ios - 如何在 swift 4 中将 GMSMapView 添加到 View 的一部分