Detecting of flat landscape / portrait orientation

Viewed 1058

Is there way to detect if it is flat and landscape or flat and portrait orientation of device ?

I am asking about that becouse I have UICollectionView in my UIViewController and in Portrait mode cells are placed in one row, in line. In Landscape they are in only column - they swaped from horizontal to vertical. I have update of collection data for every 60 seconds. After this time have to call reloadData() to actualize the data and If I will leave device *inFlat orientation, layout will get destroyed, cuz of sizeForItemAt. None of conditions would be perfect.

let isPortrait = UIDevice.current.orientation.isPortrait
if !isPortrait {
    return CGSize(width: collectionView.bounds.width, height: collectionView.bounds.height / 4)
} else {
    return CGSize(width: collectionView.bounds.width / 4, height: collectionView.bounds.height)
}

There is no way to place it like this:

let isFlat = UIDevice.currentorientation.isFlat
if isFlat && isPortrait {
//
}

It can't be in same time isPortrait and isFlat.

Is there any work around this ?

2 Answers

In my opinion, to resolve it, you should save last size of item. When our device stays in flat, sizeForItemAt will return last size of item.

var currentSize : CGSize?

override func viewDidLoad() {
  super.viewDidLoad()

  // In viewDidLoad, need to set default value for currentSize. Make sure in case
  // your app start at flat orientation, you collectionView still has a size
  currentSize = CGSize(width: collectionView.bounds.width, height: collectionView.bounds.height / 4);
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  if UIDevice.current.orientation.isPortrait {
    currentSize = CGSize(width: collectionView.bounds.width, height: collectionView.bounds.height / 4)
  } else if UIDevice.current.orientation.isPortrait {
    currentSize = CGSize(width: collectionView.bounds.width / 4, height: collectionView.bounds.height)
  }
  return currentSize;
}

Only update value of currentSize when your device stays in portrait or landscape mode. If not, use current size of item.

Related