traitCollection.horizontalSizeClass reports Compac

2019-09-10 14:31发布

问题:

I am adding a Done button in the code to the Navigation Bar for a UIViewController subclass for iPad only, more precisely for Regular Size Class with the below code. We support iOS 8+. The if statement returns Compact Size Class when run on iPad Air 2 with iOS 8.1, and it correctly reports Regular for iOS 8.4 or iOS 9. Is this a bug in iOS, or am I doing something wrong?

/// Add 'Done' button for iPad/Regular Size Class
private func addDoneButtonIfNeeded() {
    if traitCollection.horizontalSizeClass == .Regular {
        let doneButton = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: #selector(ApprovalDetailViewController.doneAction))
        doneButton.tintColor = UIColor.whiteColor()
        navigationItem.leftBarButtonItem = doneButton
    }
}

lldb output when breakpoint set on the if statement

iOS 8.1: po traitCollection.horizontalSizeClass.rawValue -> 1
iOS 8.4: po traitCollection.horizontalSizeClass.rawValue -> 2

I am using Page Sheet modal presentation on the 'iPad'.

回答1:

I resolved this by adjusting the condition like this:

presentingViewController?.traitCollection.horizontalSizeClass == .Regular