Search code examples
swiftautolayoutlandscape-portraitsize-classes

TraitCollectionDidChange behaves different for iphone X


In My case i am changing my layouts of the view depending on the traitCollection.horizontalSizeClass Here is my Code snippet .

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)

        if traitCollection.horizontalSizeClass == .regular {
            // 2
            NSLayoutConstraint.deactivate(compactConstraints)
            NSLayoutConstraint.activate(regularConstraints)
            // 3
            socialMediaView.axis = .horizontal
        } else {
            // 4
            NSLayoutConstraint.deactivate(regularConstraints)
            NSLayoutConstraint.activate(compactConstraints)
            socialMediaView.axis = .vertical
        }
    }

Every things working as directed in iphone 7 plus and iphone x in portrait-mode Screen_Shot_2018-08-07_at_1.44.54_PM.png and in landscape mode i want the rabbit image comes to left side and the stackview of all socialMedias axis will be horizontal
but in iphone X landscape mode its not coming while in phone 7 its coming .Check the below screen shots Screen_Shot_2018-08-07_at_1.32.02_PM.png


Solution

  • Looking at your question and condition, I found a problem in your condition. you should check for the verticalSizeClass instead of horizontalSizeClass.

    WHEN CHECK FOR HORIZONTAL SIZE CLASS.

    IN PORTRAIT: All iPhone Devices has compact width, so every time, it will go to else condition and set the view properly.

    IN LANDSCAPE: All iPhone Plus (iPhone 6s Plus, iPhone 7 Plus and iPhone 8 plus) Devices has Regular width and All other iPhone (iPhone 6s, 6SE, iPhone 7 and iPhone 8, iPhone X) Devices has Compact width, so for all plus devices it will works fine but not for others.

    FOR PORTRAIT: Portrait

    FOR LANDSCAPE: Landscape

    For more, read official doc here

    So, update your code to this.

    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
            super.traitCollectionDidChange(previousTraitCollection)
    
            if traitCollection.verticalSizeClass == .regular {
                NSLayoutConstraint.deactivate(compactConstraints)
                NSLayoutConstraint.activate(regularConstraints)
                socialMediaView.axis = .horizontal
            } else {
                NSLayoutConstraint.deactivate(regularConstraints)
                NSLayoutConstraint.activate(compactConstraints)
                socialMediaView.axis = .vertical
            }
        }
    

    Try and share the results.