Search code examples
iosswiftipad

Check if app is in Split View swift


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.


Solution

  • 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()
    }
    
    }