Swift4:当您有导航控制器时,如何设置顶部约束?

时间:2019-04-10 09:13:33

标签: swift uiview uiimageview constraints

screenshot 我创建了一个视图,在其中放置了图像视图和一个视图。我以编程方式向两个视图添加了约束,以使它们在我选择的每个屏幕中都完美地居中,但是当我在iPhone XSMax上启动该应用程序时,在底部出现了一个白条。因此,我想我对顶部约束有误,在拥有导航栏时如何处理顶部约束?

 func imageAndColorView() {

    view.addSubview(imageView)
    view.addSubview(colorView)
    imageView.translatesAutoresizingMaskIntoConstraints = false

    imageView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    imageView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
    imageView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    imageView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true

    colorView.translatesAutoresizingMaskIntoConstraints = false
    colorView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    colorView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
    colorView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    colorView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true

    imageView.image = UIImage(named: BackgroundImageKey)
    view.sendSubviewToBack(imageView)
    view.insertSubview(colorView, aboveSubview: imageView)
}

是的,我在viewDidLoad中称呼它。

1 个答案:

答案 0 :(得分:2)

对于上述iphoneX,您应在 topAnchor和bottomAnchor 中使用 safeAreaLayoutGuide enter image description here

func imageAndColorView() {

        view.addSubview(imageView)
        view.addSubview(colorView)
        imageView.translatesAutoresizingMaskIntoConstraints = false

        imageView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        imageView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        imageView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        imageView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true

        colorView.translatesAutoresizingMaskIntoConstraints = false
        colorView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        colorView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
        colorView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        colorView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true

        imageView.image = UIImage(named: BackgroundImageKey)
        view.sendSubviewToBack(imageView)
        view.insertSubview(colorView, aboveSubview: imageView)
    }

只需用此代码替换您的函数,它将看起来像这样,希望您的问题能得到解决。