【问题标题】:How to set autolayout so image takes up full screen?如何设置自动布局使图像占据全屏?
【发布时间】:2017-12-05 00:07:49
【问题描述】:

我有图像可以覆盖页面,但是当您旋转手机时,图像在横向时无法覆盖全屏。我错过了什么?

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
}

【问题讨论】:

  • 我注意到的第一件事是您设置了一个框架,然后关闭了自动调整大小蒙版,这意味着您正在使用自动布局。您设置了哪些限制条件?
  • 这可能会有所帮助:stackoverflow.com/a/27198660/1630618
  • 我实际上没有设置任何。我以为我可以用代码做到这一点。

标签: swift autolayout


【解决方案1】:

您可以跟踪设备的方向已更改。 到目前为止,您的代码确实使用了纵向模式的UIScreen.main.bounds

尝试使用 Notification 跟踪方向的变化,如下所示:

在 ViewDidLoad 中添加:

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

添加旋转功能:

func rotated() {
if UIDevice.current.orientation.isLandscape {
   // change frame of subview in here
} else {
   // change frame again in case you rotated back.
}
}

在选择“Portrait Upside Down”等时要小心使用它。

【讨论】:

  • 这是有道理的。谢谢!我实际上是IOS DEV的新手。如何在背景顶部设置图像?我有一系列图像,但是如何将图像设置在背景之上? et diceImage = UIImage(named: "(diceArray)") view.addSubview(diceImage) diceImage.frame = CGRect(x: 50, y: 50, width: 50, height: 50) diceImage.translatesAutoresizingMaskIntoConstraints = false diceImage.leftAnchor。约束(equalTo:view.leftAnchor,常量:50).isActive = true
  • 背景顶部是什么意思?
  • 在背景前面。 bc 当我添加图像时它没有显示在屏幕上。
  • 如何在另一个之上插入一个图像视图。这样背景就在另一个 imageview 的后面。
  • 我不确定,如果我清楚您的要求。您要向视图中添加超过 1 个子视图,并且想要在前面有 1 个特定视图?尝试使用childView.superview?.bringSubview(toFront: childView)
【解决方案2】:

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


}

【讨论】:

  • 哦。我忘了设置约束。嗯,这是有道理的。谢谢!我实际上是IOS DEV的新手。一直在为情节提要的限制而苦苦挣扎,并正在通过 youtube 寻找一种在代码中实现它的方法。
猜你喜欢
  • 1970-01-01
  • 2021-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-22
  • 1970-01-01
  • 2015-01-09
相关资源
最近更新 更多