问题
I have pretty big implementation of target actions in my UIView
subclass, so my View file (from MVC) seems to have some code, which is not really connected to arranging UIView
objects on a screen. Is it a right way to follow MVC pattern? If not, what is the right way to deal with it?
回答1:
It depends entirely what these target actions are doing.
If they’re view-related (e.g. controls to pull out menu, slide it back, move subviews, etc.) then encapsulating all of this within the view class might be reasonable.
If, however, these actions include business logic, network requests, manipulation of local data stores, etc., then squirreling them under
UIView
subclasses is likely to be the exact opposite direction of what you should do.
In terms of patterns for structuring your app, there are a host of alternatives, including:
See Dave Delong’s A Better MVC for a perspective of embracing MVC but employing techniques to keep them small and manageable.
See Medium’s iOS Architecture Patterns for a review of other approaches ranging from MVP, MVVM, Viper, etc.
See Krzysztof Zabłocki’s iOS Application Architecture for another good discussion on the topic.
I’m not going to put my thumb on the scale and advocate one particular pattern over another (this is a matter of opinion, and, as such, is off-topic for Stack Overflow), but as you go through all of the above, the consistent theme is a separation of responsibilities, making it easier to reason about our code, and improved testability.
Bottom line, moving view-specific code into your UIView
subclasses is fine, but putting business/app logic into views is an anti-pattern.
回答2:
I'm not going to speak to the proper implementation(s) of MVC as that is an exhaustive topic that can be found all over the internet. Personally, I like to encapsulate all of my view code inside a custom view subclass of UIView, and use the ViewController for managing interactions, delegates, data sources, and other events.
class CustomView: UIView {
func addSubviewsToView()
func configureLayout()
}
class CustomViewController: UIViewController {
var childView: CustomView!
func addCustomViewToViewControllerView()
func addTargetsAndGestureRecognizers()
func configureAnyViewDelegates()
func configureAnyDataSources()
}
It's possible to have a lengthy custom view class or lengthy view controller. That's not necessarily an issue. It can become an issue when there isn't an organizational pattern governing your choice.
One interesting organizational pattern for distinguishing between view and controller code is loosely outlined in this GitHub repository.
I've used bits and pieces from this concept to aid myself in organizing view and controller code. Hope this helps.
来源:https://stackoverflow.com/questions/60422316/how-to-differentiate-what-code-put-in-view-and-what-in-viewcontroller