dimanche 15 janvier 2017

Swift: How to handle tightly coupled views?

I recently had a pattern in one of my Swift projects and wasn't sure what the right way to handle it was:

I have a UIViewController that is part of a UINavigationController and I want a custom view in my navigation bar. The code is then something like this:

class MyViewController: UIViewController
    override func viewDidLoad() {
        super.viewDidLoad()
        self.customNavigationView = MyNavigationView()
        self.navigationItem.titleView = self.customNavigationView
    }
}

MyViewController and MyNavigationView are tightly coupled in a sense - they form a single piece of UI and only make sense when used together. I wonder what the preferred way to handle such cases is pattern-wise. In particular, what's the preferred way to send messages from MyNavigationView to MyViewController (such as buttons tapped).

I saw the following options:

  • Use a delegate pattern, create a MyNavigationViewDelegate protocol and add a delegate property to MyNavigationView. While the most object-oriented approach, it seems a bit "over-engineered" to me and has a lot of overhead for something that is basically a single unit of UI
  • Make MyNavigationView an inner class of MyNavigationController to indicate their strong relationship. Seems fine, but I like to have a file per class for easy navigation
  • Use a weak var targetViewController: TargetViewController? in MyNavigationView. I don't think the variable should be an optional, though, because semantically it is not
  • Use a let targetViewController: TargetViewController and a custom initializer in MyNavigationView that sets it. Seems the best option to me right now, but I'm not sure if it can create a memory leak since its a strong reference cycle

I wonder what other people's thoughts on this are. Is there are clear pattern that should be used here or is it a matter of taste?

Aucun commentaire:

Enregistrer un commentaire