iOS Development

ios – Is it attainable to alter a customized trait from a dad or mum trait assortment and observe the modifications to all view controllers?

Spread the love


I am attempting to create a customized trait object and put it into the UITraitCollection class utilizing some new APIs in iOS 17. For instance, what I need to do is create a number of app theme traits, put them into the trait assortment class, and make the entire present out there UIViewController objects to watch the theme trait modifications. I am conscious that in iOS 17, UIKit has a brand new methodology to override a trait definition by mutating the brand new traitOverrides property. However primarily based on the WWDC23 video session, Apple informed us to make use of this property just for particular view controllers or views and all of its kids/subviews. So the modifications do not replicate to the entire view controllers which can be presently out there in reminiscence. This is what I did to date:

Creating a brand new customized UITraitDefinition:

enum ThemeTraitType: Int {
    case mild
    case darkish
    case monochrome
}

struct ThemeTrait: UITraitDefinition {
    typealias Worth = ThemeTraitType
    
    static let defaultValue: ThemeTraitType = .mild
    static var title: String = "Theme"
    static var affectsColorAppearance: Bool = true
}

Added it into the UITraitCollection class utilizing extensions:

extension UITraitCollection {
    var currentTheme: ThemeTraitType { self[ThemeTrait.self] }
}

extension UIMutableTraits {
    var currentTheme: ThemeTraitType {
        get { self[ThemeTrait.self] }
        set { self[ThemeTrait.self] = newValue }
    }
}

Register the trait modifications observer:

remaining class ViewController: UIViewController {
    
    override func viewDidLoad() {
        tremendous.viewDidLoad()
        
        registerForTraitChanges([ThemeTrait.self], handler: { (self: Self, previousTraitCollection: UITraitCollection) in
            // Do one thing right here...
        })
    }

}

Change the currentTheme trait utilizing the brand new traitOverrides property:

traitOverrides.currentTheme = .darkish

This works as anticipated for the view controller the place I alter the trait from. However as an example I am utilizing a UINavigationController and have 5 view controllers contained in the navigation controller and I alter the trait contained in the final view controller (which is the fifth view controller contained in the stack), once I return to the earlier view controller, the trait modifications would not replicate on the entire earlier view controllers. What I need to do is the modifications I’ve made inside any view controllers may even replicate to the entire out there view controllers that presently exist in reminiscence. Is that this attainable to implement? Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *