【问题标题】:What to use instead of UIScreen.mainScreen().applicationFrame for swift in ios 9.1?在 ios 9.1 中使用什么来代替 UIScreen.mainScreen().applicationFrame 来实现 swift?
【发布时间】:2015-10-31 08:43:00
【问题描述】:

这可能是一个简单的问题,但由于我是初学者,最好问一下。

正如标题所说,我应该使用什么来代替 UIScreen.mainScreen().applicationFrame,因为它在 9.0 中已被弃用。

如果可能的话,如果你能给我提供一个样本或示例,那就太好了,因为我发现 Apple 的文档很困难。

目前我使用下面的代码,但我希望将其更改为新版本。我很想收到您的来信!

  let sizeRect = UIScreen.mainScreen().applicationFrame
  let posX = arc4random_uniform(UInt32(sizeRect.size.width))
  let posY = arc4random_uniform(UInt32(sizeRect.size.height))
  Enemy.position = CGPoint(x: CGFloat(posX), y: CGFloat(posY))

【问题讨论】:

  • 你可以使用 UIScreen.mainScreen().bounds.size。

标签: ios iphone xcode swift


【解决方案1】:

使用

let rect1 = UIScreen.mainScreen().bounds // Returns CGRect
let rect2 = UIScreen.mainScreen().bounds.size // Returns CGSize

Swift 3+:

let rect1 = UIScreen.main.bounds // Returns CGRect
let rect2 = UIScreen.main.bounds.size // Returns CGSize

【讨论】:

    【解决方案2】:

    我知道UIScreen.mainScreen().bounds 是推荐的替代方案;但是,它并不完全等同于UIScreen.mainScreen().applicationFrame,尤其是当您的应用程序不占据整个屏幕时,这会发生在某些 iPad 上的 Split View 和 Slide Over 功能中。

    在这种情况下,这是一个不错的选择: UIApplication.sharedApplication.keyWindow.frame。 (当然keyWindow 必须可用,也就是说,你确实调用了makeKeyAndVisible

    【讨论】:

    • 这就是答案。 UIScreen.main.bounds 在某些情况下(例如,当您打电话时)起作用。
    • 我同意这就是答案。例如,如果您的应用程序与另一个应用程序并排运行,您可以为 Obj-C 执行 self.window.frame = UIApplication.shared.keyWindow.boundsself.window.frame = [UIApplication sharedApplication].keyWindow.bounds;,大多数情况下人们会在此之后调用 makeKeyAndVisible 但在这种情况下,您必须先这样做Stepheneye 说否则你会从 keyWindow 得到一个 nil 值。
    【解决方案3】:

    从 swift 3 开始,您现在需要像这样使用它。

    let SCREEN_WIDTH = UIScreen.main.bounds.size.width
    let SCREEN_HEIGHT = UIScreen.main.bounds.size.height
    

    【讨论】:

      【解决方案4】:

      为:

      let width = UIScreen.mainScreen().bounds.width
      

      对于:

      let height = UIScreen.mainScreen().bounds.height
      

      【讨论】:

        【解决方案5】:

        斯威夫特 3+:

        let width = UIScreen.main.bounds.width
        let height = UIScreen.main.bounds.height
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-11-24
          • 1970-01-01
          • 2020-05-15
          • 2011-10-02
          • 2011-10-12
          相关资源
          最近更新 更多