view.traitCollection.horizontalSizeClass returning undefined (0) in viewDidLoad

前端 未结 5 577
忘掉有多难
忘掉有多难 2021-02-12 13:19

I\'m using a UITextView inside a UIPageViewController, and I want to determine the font size based on the size class of the device.

The first slide of the page view is l

5条回答
  •  误落风尘
    2021-02-12 14:12

    In my case I needed my view to know about the horizontalSizeClass so accessing the UIScreen traitCollection was tempting but not encouraged, so I had something like this:

    override func layoutSubviews() {
        super.layoutSubviews()
        print("\(self.traitCollection.horizontalSizeClass.rawValue)")
    
        switch self.traitCollection.horizontalSizeClass {
        case .regular, .unspecified:
            fontSize = 28
    
        case .compact:
            fontSize = 20
        }
    }
    
    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        print("\(self.traitCollection.horizontalSizeClass.rawValue)")
    
        guard let previousTraitCollection = previousTraitCollection else { return }
    
        if self.traitCollection.horizontalSizeClass != previousTraitCollection.horizontalSizeClass {
            layoutIfNeeded()
        }
    }
    

提交回复
热议问题