Alexei
Alexei

Reputation: 510

Display NSViewController's view as NSView's (NSScrollView) subview

I have different NSViewControllers that have multiple fields. One has NSDatePicker, another has NSTextField and so on.

Example: CustomViewController

The idea is to display these in NSScrollView when I click on particular buttons.

ScrollViewWithViews

So I came up with the next solution:

My main ViewController class has a variable viewControlers: [ViewController] that holds all the custom ViewControllers (with different inputs). When I click on button I initialize certain ViewController, and then add it's view to the scroll view.

Examle:

let dmyVC = storyBoard.instantiateController(withIdentifier: "DayMonthYearVC") as! DayMonthYearSelectVC
self.viewControlers.append(dmyVC) //add new vc to the array 
scrollView.addSubview(dmyVC.view) //add this VC’s view to a scroll view

I added NSButton that triggers “close()” function to every custom ViewControllers with inputs. Then on those ViewControllers in the “close” function I do:

self.view.removeFromSuperview()

However it only removes a ViewController’s view from the scrollView, but the ViewController itself is not deallocated and it remains in the viewControlers array (variable inside mainViewController)

I was thinking of creating delegates, and call a delegate method every time when close button on one of those views is pressed. In this case I simply need to have an array of delegates (for every custom ViewController) [parallel to the array that holds references to all those ViewControllers that were created].


Now I think, is there a common way of dealing with a situation when you want to present ViewControllers’ views inside another view, or everyone does it in a way they like better?

Upvotes: 0

Views: 331

Answers (1)

Willeke
Willeke

Reputation: 15589

Solution A: a delegate. All view controllers can have the same delegate, the main view controller. The closing view controller is a parameter of the delegate method.

Solution B: a custom notification. The main view controller observes the notification. The closing view controller posts the notification and is the object of the notification.

Upvotes: 1

Related Questions