Search code examples
iosiphoneuiviewuikituiresponder

Does implementing UIResponder touch methods inside a UIView subclass violate MVC?


The following UIResponder methods report raw touches on screen:

- touchesBegan:withEvent:
- touchesMoved:withEvent:
- touchesEnded:withEvent:

Recently I was playing with a UIView subclass that I wanted to be touch responsive.

Initially I implemented the methods above in the UIViewController that was responsible for the view in question.

However, I realised that the touch methods were being called whenever the UIViewControllers view was being touched, not the subview I wanted.

I reimplemented the methods inside a UIView subclass and everything worked as expected.

However I feel like this is violating MVC. I have control logic inside my view.

Should I keep the methods implemented inside the UIViewController instead, and somehow hit test to interpret which view was touched, or am I correct in having the methods implemented inside the UIView subClass?

I feel like the later is the lazy way out.

Thanks for your time.


Solution

  • In MVC, the view is responsible for user interaction. Therefore, it makes more sense to have your UIResponder methods overridden in your UIView. To keep strictly with MVC, you should then use a delegate pattern (or some other pattern) to call control logic functions that are in your controller.

    enter image description here

    The above image is from (Apple's MVC documentation). The part that pertains to your question is in the upper left. The view should tell the controller it has been touched ect, and the controller should execute the logic.

    The UIViewController only is able to implement these methods because it comes with a built in view. This is confusing because it means that the UIViewController itself violates MVC, but thats a more involved discussion.