以编程方式创建的 UIViewController 部分被导航栏隐藏

Programmatically created UIViewController partially hidden by navigation bar

我有一个 UIViewController subclass 是我以编程方式创建的,没有使用 Interface Builder。 class 被称为 ColorController,因为它编辑了一种颜色。当我将它添加到 UINavigationController 内的弹出窗口时,其内容隐藏在导航栏下方。当从 IB 故事板文件中提取 ColorController 时,这种情况过去不会发生。

是否有一些 属性 或方法我必须覆盖我的 ColorController 以告诉它在导航控制器中调整其边界?

现在我所做的就是创建我的根 UIViewColorPicker)并将其设置为 loadView() 中的 self.view

class ColorController: UIViewController {

    private let colorPicker: ColorPicker       

    init() {
        colorPicker = ColorPicker()
    }

    override func loadView() {
        self.view = colorPicker
    }

不要覆盖 loadView,覆盖 viewDidLoad 并添加 colorPicker self.view

使用 SnapKit

colorPicker.snp.makeConstraints { (make) -> Void in
    make.leading.trailing.bottom.equalTo(0)
    make.top.equalTo(self.topLayoutGuide.snp.bottom);
}

使用iOS UIKit

colorPicker.translatesAutoresizingMaskIntoConstraints = false

var constraints = [NSLayoutConstraint(item: colorPicker, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 0),
                           NSLayoutConstraint(item: colorPicker, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: 0),
                           NSLayoutConstraint(item: colorPicker, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1, constant: 0)]

if #available(iOS 11.0, *) {
    constraints.append(NSLayoutConstraint(item: colorPicker, attribute: .top, relatedBy: .equal, toItem: self.view.safeAreaLayoutGuide, attribute: .top, multiplier: 1, constant: 0))
} else {
    constraints.append(NSLayoutConstraint(item: colorPicker, attribute: .top, relatedBy: .equal, toItem: self.topLayoutGuide, attribute: .bottom, multiplier: 1, constant: 0))
}
self.view.addConstraints(constraints)