Many of us, admittedly, will slightly grease the MVC lines and slip into our controllers with a bit of code related to browsing. I personally think that everything is in order. This does not diminish the fact that we still mainly follow the MVC pattern (and that Cocoa classes do a heavy lifting for presentation). But for me, if the code associated with the view goes beyond the trivial, I find that I choose a subclass of the view.
There will be people who are religiously subclass of UIView , but I think a little pragmatism is justified. If you add a trivial amount of code related to viewing, is your code clarity improved by abstracting from this in a new subclass of UIView ? Not always. But I think that this situation (when someone subclasses, when they probably do not need), is much less common than the opposite problem (when someone is not subclasses, when they probably should).
So you asked:
I do not see the need to do this [subclassing UIView], unless, of course, you reuse the same UIView in several places or do not execute your own drawing.
I agree that reuse and custom drawing (e.g. drawRect ) are two great examples. But I would also add the principle that if a subclassification would improve the clarity of the code, because the presentation is quite complex (admittedly a subjective call), then I will be a subclass. Two examples:
I had a calendar view in the application, and the view controller became cumbersome, managing all cells for different days of the month, etc. Thus, by subclassing UIView , I was able to abstract the ugly details of all subzones made up of a calendar view. I have subclassed not only the main “month”, but also the “daytime” views in the “month” view. No reuse as such. No custom drawing. But that was the right decision. The code is infinitely more legible.
I am increasingly subclassing UITableViewCell for my table views. In my first projects, I would have a table view controller cellForRowAtIndexPath to make all the complex composition and layout of this cell. My code is much easier to follow now that I usually subclass UITableViewCell in any situation where I don't use one of the standard cell types.
In short, although I agree that you should not force a subclass of a UIView for each view controller, I personally try to do this when the view reaches a certain level of complexity. I let code intelligibility manage my practices. I find that I subclass representations more than before, but by no means do this all the time.
On the bottom line, while you don’t need to constantly look at subclasses, I personally believe that many developers are guilty of the impossibility of subclassing (or models) when they should have. They should not do this because of some fanatical desire to comply with MVC, but rather should ask themselves if their code will be easier to read and maintain if they subclass the view or model as necessary.
source share