如何设置固定的布局约束?

时间:2019-05-10 11:33:38

标签: ios swift autolayout

我正在以编程方式创建地图UI。我希望视图的顶部在UINavigationBar之后开始,并且屏幕底部的底部空间为250。我已经添加到以下代码:

private lazy var mapView: GMSMapView = {
    let mv = GMSMapView(frame: CGRect.zero)
    mv.settings.myLocationButton = true
    mv.isMyLocationEnabled = true
    mv.translatesAutoresizingMaskIntoConstraints = false
    return mv
}()

override func loadView() {
    let screenSize = UIScreen.main.bounds
    let v = UIView(frame: CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height))
    v.backgroundColor = UIColor.white
    view = v
    updateMap()
    view.addSubview(mapView)
}

override func viewDidLoad() {
    super.viewDidLoad()
    initConstraints()
}

func initConstraints() {
    guard let navVC = navigationController else { return }
    NSLayoutConstraint.activate([
        mapView.topAnchor.constraint(equalTo: view.topAnchor, constant: navVC.navigationBar.frame.maxY),
        mapView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0),
        mapView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0),
        mapView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -200)  // not working properly
    ])
}

在此处设置底部锚点时,顶部也会产生相等的间距,这是我不理解的。请参阅所附的屏幕截图。

map view controller

如何删除顶部空间,但保留底部空间?

2 个答案:

答案 0 :(得分:0)

只需替换

mapView.topAnchor.constraint(equalTo:view.topAnchor,constant:navVC.navigationBar.frame.maxY)

使用

mapView.topAnchor.constraint(equalTo: view.topAnchor, constant:0)

constant:navVC.navigationBar.frame.maxY

  

表示非安全区域的UIView Y位置将为64像素   设备和88像素(具有安全区域的设备)

最终代码:

func initConstraints() {
    guard let navVC = navigationController else { return }
    NSLayoutConstraint.activate([
        mapView.topAnchor.constraint(equalTo: view.topAnchor, constant:0),
        mapView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0),
        mapView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0),
        mapView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -200)  // not working properly
    ])
}

答案 1 :(得分:0)

问题是我添加了mapView.center = view.center来创建此问题。删除此语句可解决此问题。