如何设置自动布局使图像占全屏?

时间:2017-12-05 00:07:50

标签: swift autolayout

我有覆盖页面的图像,但是当您旋转手机时,图像并未覆盖横向全屏。我错过了什么?

func setBackgroundImage() {
    let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
    backgroundImage.image = UIImage(named: "newbackground")
    backgroundImage.contentMode = UIViewContentMode.scaleAspectFill
    self.view.insertSubview(backgroundImage, at: 0)
    backgroundImage.translatesAutoresizingMaskIntoConstraints = false
}

2 个答案:

答案 0 :(得分:0)

您可以跟踪设备的方向已更改。 到目前为止,您的代码确实使用纵向模式的l = [[2,3],[5,6],[4,8]] for item in l: print(item[0], end = ' ') print() #take note this needs to be outside both loops for obj in l: print(obj[1], end = ' ')

尝试使用UIScreen.main.bounds跟踪方向更改,如下所示:

ViewDidLoad中的

添加:

Notification

添加旋转功能

    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)

小心使用此选项可以选择Portrait Upside Down等。

答案 1 :(得分:0)

translatesAutoresizingMaskIntoConstraints之后的又一步,设置并激活自动布局约束。

func setBackgroundImage() {
    let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
    backgroundImage.image = UIImage(named: "newbackground")
    backgroundImage.contentMode = UIViewContentMode.scaleAspectFill
    self.view.insertSubview(backgroundImage, at: 0)

    backgroundImage.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        backgroundImage.leftAnchor.constraint(equalTo: view.leftAnchor),
        backgroundImage.rightAnchor.constraint(equalTo: view.rightAnchor),
        backgroundImage.topAnchor.constraint(equalTo: view.topAnchor),
        backgroundImage.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ])


}