Tel Tel - 3 months ago 24
Swift Question

How to to determinate in Swift the current width of the app when in Split View?

EDIT: I have a project with a row of buttons on top on it. Usually the buttons are 5 in Compact view and 6 in Regular view. I would like to remove a button when the app runs in 1/3 Split View. How can I determine the width of the app?

I'm using this code to determinate the current width of the app when 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)
}


It works, but unfortunately applicationFrame is deprecated in iOS 9, so I'm trying to replace it with this:

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


The problem is that the first statement gives you the effective width of the app and it's fine, instead the second one, gives you the width of the screen, so you can't use it to learn the real width of the app when it is in Split View.

Would someone know what code would be necessary to replace this deprecated statement?

let currentWidth = UIScreen.mainScreen().applicationFrame.size.width // deprecated

Answer

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.

Comments