Search code examples
swiftxcodemacosdesktop-applicationxcode-storyboard

Creating a List of Custom Views in Xcode


I'm currently working on developing a desktop application for MacOS for downloading batches of audio files from URLs at one time I've run into a question about UI design that I can't figure out.

I have a class called SongEntry.swift that holds information regarding the URL that was entered (e.g. url, title, length, author, etc.) and I want to create a vertically growing list of custom views that updates when a new one is added.

Where is what the base view looks like:

enter image description here

Inside of the big white area is where I want the list to be held.

I've tried to create a separate view controller that handles each entry but that didn't work. I know UI design for MacOS is much different from iOS, however I think what I'm looking for is a way to simulate the table views and cell prototypes from iOS but can't find a suitable option.

If anyone knows of a possible solution or can point me in the right direction, I'd greatly appreciate it!


Solution

  • What you want is one of the collection views. For vertical list, you'll probably use NSTableView with only one column and hide everything else like headers.

    Here are roughly the steps you need:

    • You can use your existing view controller or create a dedicate view controller for just the table (and use the 'embed' option in Interface Builder)
    • This view controller will adopt the NSTableViewDataSource and NSTableViewDelegate protocols to provide the data (your SongEntry objects) and the view for each row.
    • You set your NSTableView's source and delegate to your view controller.
    • You create a view which will serve as your "cell", it will be used by each row to display the data. You can design it either in IB or in code.

    The entire process is described in detail in the Table View Programming Guide for Mac.

    This topic can be a bit confusing. Note that there are two main approaches: the view-based and NSCell-based tables. Don't bother with the NSCell way, it's more of a legacy leftovers.

    Also note that there are some overlap of methods in both NSTableViewDataSource and NSTableViewDelegate to provide data and views that can be a bit confusing at first. Just play around with the code and samples and it will be clearer which delegate method to use when.

    There are many examples both on Apple's developer site and github. Also a good tutorial on raywenderlich.com.