I have an iOS 9 project with a deployment target of iOS 7.1, using Xcode 7 beta 4. I can't find a way in a UIViewController to override the traitCollectionDidChange method.
I've added this to a view controller:
override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) {
// ...
}
The compiler gives the error:
Foo.swift:142:66: 'UITraitCollection' is only available on iOS 8.0 or newer
True enough. The source editor provide two popup suggestions:
Add @available attribute to enclosing instance method.
Add @available attribute to enclosing class.
Suggestion #2 is out of the question (the view controller is needed in iOS 7.1). When clicking suggestion #1, it changes the code as follows:
@available(iOS 8.0, *)
override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) {
// ...
}
This leads to a new compiler error:
Overriding 'traitCollectionDidChange' must be as available as declaration it overrides.
I'm able to override traitCollectionDidChange in Objective-C but not Swift 2. Bug? Suggestions?
Thanks for your original post, I've just found myself facing the same issue today while converting my project to Swift 2.
Here's a possbile workaround I am experimenting with and that should allow you to keep your deployment target to 7.0:
- Keep your UIViewController (let.s call it ParentViewController) as it is, available for all supported OS versions (don't decorate ParentViewController with @available)
- Silent the compiler by removing the override of traitCollectionDidChange
- Create ViewControllerWithAdaptiveBehaviour as a subclass of ParentViewController and make it override traitCollectionDidChange
- Declare the latter as @available(iOS 8.0, *) to silence the usual compiler's moaning
- At run time, conditionally load ParentViewController or ViewControllerWithAdaptiveBehaviour depending of the OS version at runtime.
This should work, hope it helps