Search code examples
uikituisplitviewcontrollermac-catalyst

How to preserve split view divider configuration in Mac Catalyst app?


Mac apps that have a sidebar (Mail, Finder, etc) allow you to resize its width, and that width is preserved across app launches. You enable this behavior in an AppKit app by assigning autosaveName on your NSSplitView. How do you do this in a Mac Catalyst app using UISplitViewController?

By default, my Catalyst app's sidebar is pretty wide, so every time the user opens it they have to resize it.


Solution

  • I reached out to a friend who was able to achieve this in their app. They said you can manually save the current width to UserDefaults and upon creating the split view controller set its preferredPrimaryColumnWidth to the last saved width. Nice!

    In my UISplitViewController subclass I added:

    init() {
        let lastWidth = UserDefaults.standard.integer(forKey: "SidebarWidth")
        let initialWidth = lastWidth > 0 ? CGFloat(lastWidth) : 220
        preferredPrimaryColumnWidth = initialWidth
        
        //...
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        UserDefaults.standard.setValue(Int(primaryColumnWidth), forKey: "SidebarWidth")
    }