Search code examples
iosswiftviewarchitectural-patterns

What is the right way of using Views in iOS development?


I have a customView. It has some condition like this(only example):

customView(viewsNeed: Bool)

...

if viewsNeeded {
    self.addSubView(newView)
    self.addSubView(newView2)
} else {
    self.addSubView(newView3)
    self.addSubView(newView4)
    self.addSubView(newView5)
}

and then I can add this View to in my ViewController:

self.view.addSubView(customView(viewsNeeded))

What I want to know is what should I do? Write conditions like this, or make separate Views for this purpose. Something like:

View1

...

self.addSubView(newView)
self.addSubView(newView2)

View2

...

self.addSubView(newView3)
self.addSubView(newView4)
self.addSubView(newView5)

And add one of them in the ViewController:

if viewsNeeded {
    self.view.addSubView(view1)
} else {
    self.view.addSubView(view2)
}

What kind of View creating is better in what situation, and how should i decide this kind of things? I need some really wide answers with explanations if it's real.


Solution

  • If a view can have different states, you would take care of those different states within the view that has a certain responsibility. The UINavigationBar is a good example. It has a clear purpose, giving navigational context to the user, but it's state (and context) can make it appear different.

    func pushNavigationItem(...) {
      ...
      if self.items.count > 1 {
         // show backButton
      } else {
         // hide backButton
      }
    }
    

    If the different views don't work together for a shared purpose, I wouldn't group them together in a container-view, but instead add them separately, dependent on your needs in a ViewController.

    override func viewDidLoad() {
      if userDidBuyContent() {
        // add view with bought content
      } else {
        // add view to buy content
      }
    }
    

    And in general it's a good practice to keep your view-hierachy as flat as possible. The less views you introduce, the better your app will perform. The decision is ultimately up to you, but just keep in mind what the purpose of a view is and whether subviews contribute to that purpose or are really serving some other purpose.