从ChildViewController添加的ImageView中的特殊上边距

时间:2018-10-14 03:46:58

标签: ios swift childviewcontroller

我创建了一个如下所示的子视图控制器。它有一个UIImageView。我将UIImageView添加到视图中,如下所示。

class SampleChildViewController : UIViewController {

    let imageView : UIImageView = {
        let imageview = UIImageView()
        imageview.translatesAutoresizingMaskIntoConstraints = false
        imageview.clipsToBounds = true
        imageview.contentMode = .scaleAspectFit
        imageview.image = UIImage(named: "cat")
        return imageview
    }()


    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(imageView)

        NSLayoutConstraint.activate([
            imageView.topAnchor.constraint(equalTo: view.topAnchor),
            imageView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 10),
            imageView.widthAnchor.constraint(equalToConstant: 150),
            imageView.heightAnchor.constraint(equalToConstant: 150)
            ])
    }


}

这是父视图控制器的外观。

class ViewController: UIViewController {

    let child : SampleChildViewController = SampleChildViewController()


    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.red

        child.view.translatesAutoresizingMaskIntoConstraints = false
        addChild(child)
        child.didMove(toParent: self)
        view.addSubview(child.view)



        NSLayoutConstraint.activate([
            child.view.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 8),
            child.view.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 8),
            child.view.leftAnchor.constraint(equalTo: view.leftAnchor),
            child.view.rightAnchor.constraint(equalTo: view.rightAnchor),
            ])



    }


}

现在的问题是,我的imageview的顶部空白很奇怪,如下所示。如何解决?

enter image description here

1 个答案:

答案 0 :(得分:1)

问题出在imageview.contentMode = .scaleAspectFit上。您为图像看到的边界不是真实边界。将内容模式设置为imageview.contentMode = .scaleAspectFill,因为它将填充整个视图。

它应该在下面看起来

let imageView : UIImageView = {
    let imageview = UIImageView()
    imageview.translatesAutoresizingMaskIntoConstraints = false
    imageview.clipsToBounds = true
    imageview.contentMode = .scaleAspectFill
    imageview.image = UIImage(named: "cat")
    return imageview
}()