uikitwidthios9splitview

UIKit - How to determine width of the app window in Split View?


I have a project with a row of buttons at the top of the UI. There are five buttons shown in Compact view, and six in Regular view. I would like to remove a button when the app runs in 1/3rd Split View.

How can I determine the width of the app window?

I'm using this code to determine the width in Split View (multitasking):

override func viewWillTransitionToSize(size: CGSize, 
withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
            
    // works but it's deprecated:
    let currentWidth = UIScreen.mainScreen().applicationFrame.size.width
         print(currentWidth)
    }
}

This works, but UIScreen.mainScreen().applicationFrame is deprecated in iOS 9.

So I'm trying to replace it with the following, but it gives the the width of the screen, which is not what I need:

override func viewWillTransitionToSize(size: CGSize,
withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
            
    // gives you the width of the screen not the width of the app:
    let currentWidth = UIScreen.mainScreen().bounds.size.width
        print(currentWidth)
    }
}

What can replace the deprecated statement?


Solution

  • You can just get the size of the parent view.

    let currentSize = self.view.bounds.width
    

    That will return the width accurately even in split view.

    You can do something like this to determine whether to show or hide a button.

    let totalButtonWidth: Int
    for b in self.collectionView.UIViews{
        let totalButtonWidth += b.frame.width + 20 //Where '20' is the gap between your buttons
    } 
    if (currentSize < totalButtonWidth){
        self.collectionView.subviews[self.collectionView.subviews.count].removeFromSuperview()
    }else{
        self.collectionView.addSubview(buttonViewToAdd)
    }
    

    Something like that, but i think you can get the idea.