1

I want to make a couple things happen in my swift iPhone/iPad app when it is in split view or running on an iPhone. Based on this answer (Detect if app is running in Slide Over or Split View mode in iOS 9), I have figured out how to do this in Objective-C. I am not using a split view controller (stress on the couple of minor things to happen if split view is active). Is it possible to check the width of the app window in live time?

Basically, I just want something to happen in my app when the window width is below a certain value.

Community
  • 1
  • 1
owlswipe
  • 19,159
  • 9
  • 37
  • 82

2 Answers2

0

As a proxy for splitView, you can test if the app is full screen with following function

func isFullScreen() -> Bool {
    let appRect = UIApplication.shared.windows.first?.frame ?? CGRect.infinite
    let screenRect = UIScreen.main.bounds
    return appRect.width == screenRect.width && appRect.height == screenRect.height
}

Not being full screen is however not fully specific to split view. Image in image, slide over are also not full screen. More important, M1 Mac running an iPad app will also likely return false.

J Kasparian
  • 465
  • 2
  • 7
-4

To my knowledge, I've made the first uncomplicated split view detector in swift (thanks Ulysses R.)! So taking Ulysses's advice, I'm using let width = UIScreen.mainScreen().applicationFrame.size.width to detect the width of my app's window. To have the computer check the width over and over again, I am running an NSTimer every hundredth of a second, then doing stuff if the width is higher/lower than something.

Some measurements for you (you have to decide what width to make stuff occur above/below): iPhone 6S Plus: 414.0
iPhone 6S: 375.0
iPhone 5S: 320.0
iPad (portrait): 768.0
iPad (1/3 split view): 320.0
iPad Air 2 (1/2 split view): 507.0
iPad (landscape): 1024.0

Here's a code snippet:

class ViewController: UIViewController {

var widthtimer = NSTimer()

func checkwidth() {

    var width = UIScreen.mainScreen().applicationFrame.size.width

    if width < 507 { // The code inside this if statement will occur if the width is below 507.0mm (on portrait iPhones and in iPad 1/3 split view only). Use the measurements provided in the Stack Overflow answer above to determine at what width to have this occur.

        // do the thing that happens in split view
        textlabel.hidden = false

    } else if width > 506 {

        // undo the thing that happens in split view when return to full-screen
        textlabel.hidden = true

    }
}


override func viewDidAppear(animated: Bool) {

    widthtimer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: "checkwidth", userInfo: nil, repeats: true) 
// runs every hundredth of a second to call the checkwidth function, to check the width of the window.

}

override func viewDidDisappear(animated: Bool) {
    widthtimer.invalidate()
}

}
owlswipe
  • 19,159
  • 9
  • 37
  • 82