Search code examples
iosswiftuiviewcontrolleriphone-x

Swift: safe area on iPhone


I have ViewController with collectionView and collectionView bottom, top, leading, trailing constraints to superview. And on iPhone 8 my screen look like this:

enter image description here

And for another devices all looks fine. But on iPhone X look like this:

enter image description here

I use this code for my cells:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let offset: CGFloat = 10
    let width = collectionView.bounds.width / 3  - offset * 4
    let a: CGFloat = width / 2
    let b: CGFloat = a * 3 + a * 0.65
    let height = b

    return CGSize(width: width, height: height) 

    }

How to fix it?

Update

constraints:

enter image description here


Solution

  • With your details I got below output.

    enter image description here

    NOTE: In landscape mode safearea of top is zero.

    Constraints :

    enter image description here

    SizeForItem :

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            let offset: CGFloat = 10
            let width = collectionView.bounds.width / 3  - offset * 4
            let a: CGFloat = width / 2
            let b: CGFloat = a * 3 + a * 0.65
            let height = b
    
            return CGSize(width: width, height: height)
        }
    

    Edit : Check is this o/p is not for you or not. So that I will explain. And if you wanted to cover the safe area then it is not possible.

    Iphone X

    enter image description here

    Iphone 8

    enter image description here