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

How to set a fixed layout constraint?

我正在以编程方式创建地图 UI。我希望视图的顶部在 UINavigationBar 之后开始,底部 space 从屏幕底部开始 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
    ])
}

这里设置底部锚点时,等于space也从顶部去掉,我不明白。请参阅随附的屏幕截图。

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

只需更换

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

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

常数:navVC.navigationBar.frame.maxY

Means your UIView Y Position will be 64 pixels for non-safe area device and 88 pixels for a device with safe area

最终代码:

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
    ])
}

问题是我添加了 mapView.center = view.center,这导致了这个问题。删除此语句解决了问题。