Swift: safe area on iPhone

2019-09-02 05:16发布

问题:

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

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

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:

回答1:

With your details I got below output.

NOTE: In landscape mode safearea of top is zero.

Constraints :

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

Iphone 8