【发布时间】:2018-07-12 08:33:51
【问题描述】:
我正在视图中显示地图。我正在使用自动布局,这就是为什么我在 viewDidLayoutSubviews() 中调用创建地图视图函数的原因。 viewDidLayoutSubviews() 调用了两次并创建了两次地图,但初始地图未从视图中删除。当我在 viewDidLoad() 中调用创建地图视图函数时,它只创建一次并且不适合视图框架。
我的代码是...
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
print("viewDidLayoutSubviews")
loadMapView()//Call map view function
let width = mapSubView.frame.size.width
let x = mapSubView.frame.minX
let y = mapSubView.frame.minY
searchBar.frame = CGRect(x: x+10, y: y+10, width: width, height: 40)
mapSubView.addSubview(searchBar)
searchBar.delegate = self
// hide cancel button
searchBar.showsCancelButton = true
// set Default bar status.
searchBar.searchBarStyle = UISearchBarStyle.default
let y1 = searchBar.frame.maxY
searchTableView.frame = CGRect(x: x, y: y1, width: width, height: searchTableView.frame.size.height)
mapSubView.addSubview(searchTableView)
searchTableView.delegate = self
searchTableView.dataSource = self
}
//Create map view
func loadMapView() {
// Create a GMSCameraPosition that tells the map to display the
// coordinate -33.86,151.20 at zoom level 6.
let camera = GMSCameraPosition.camera(withLatitude: 19.3822559, longitude: 80.2194394, zoom: 6.0)
let mapView = GMSMapView.map(withFrame: CGRect(x: 1, y: 1, width: mapSubView.frame.size.width-2, height: mapSubView.frame.size.height-2), camera: camera)
mapSubView.addSubview(mapView)
print("map : \(mapSubView.frame.size.height)")
print("map : \(mapView)")
// Creates a marker in the center of the map.
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: 19.3822559, longitude: 80.2194394)
marker.title = ""
marker.snippet = ""
marker.map = mapView
}
如何在我的 mapSubView 中放置地图?
【问题讨论】:
-
您应该在您设置屏幕其他布局的地方布局 MapView,或者在 viewDidLoad 中使用适当的约束创建它。您永远不应该在 viewDidLayoutSubviews 方法中调用 addSubView,因为它会被多次调用(例如,当您将设备旋转到横向时)。
-
@Péter Kovács 非常感谢您.. 我会尝试...
标签: ios swift google-maps ios-autolayout autolayout