将代码嵌入once var中
var once = true
/ /
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
print("viewDidLayoutSubviews")
if once {
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
once = false
}
}
或在中使用约束
viewDidLoad
mapView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate( [
mapView.leadingAnchor.constraint(equalTo: mapSubView.leadingAnchor, constant: 0),
mapView.trailingAnchor.constraint(equalTo: mapSubView.trailingAnchor, constant: 0),
mapView.topAnchor.constraint(equalTo: mapSubView.topAnchor, constant: 0),
mapView.bottomAnchor.constraint(equalTo: mapSubView.bottomAnchor, constant: 0),
])