Passing array of UIViews or structs to UIViewController

Viewed 142

In order to fulfill the promise of MVC I have a question regarding creating structs or not. Right now, an array of customs UIViews are passed to a ViewController which arranges them.

The custom UIView looks for example like this

class TopView: UIView {
    private var text: String 
    private var question: String
    private var explanation: String 

    required init(text: string,...) {
        self.text = text    
        ...   
    }
 ....
}

Then those UIViews are passed as an array to a View Controller and a function inside will arranges them. Therefore, lots of arrays of UIViews are stored like this

let derivative: [UIView] = [TopView(text: "", ....),
                            MainBodyView(text:"",...), 
                            BottomView(text:"",...)
                            ]

So, to have a clear and good code structure I want to know if it better to create structs containing all these information and a function inside the ViewController which extracts the information and put them into views. Or are there better ways to do it ?

1 Answers

The arrays of UIViews will contain always a TopView, MainBodyView and a BottomView. The only difference is in the number of MainBodyView. There can be for example 10 oder 5 MainBodyViews.

Passing views around is very messy and completely violates MVC. It sounds like what you really want to pass here is an instance of a custom configuration struct. For example (this is minimal, just expand it as needed):

struct Config {
    struct VConfig {
        let text: String
    }
    let topViewConfig: VConfig
    let bodyViewConfigs: [VConfig]
    let bottomViewConfig: VConfig
}

Now pass the data and let the target view controller worry about what that means for purposes of views.

This makes sense because you, meaning the first view controller who is assembling this data and passing it to the target view controller, are not in charge of the target view controller's views — you have no business knowing anything about them or touching them in any way. Plus, this way, if it happens that the target view controller uses a storyboard to instantiate the actual views, no problem, as you are agnostic about that (and rightly, as it is none of your business).

Related