开发者

UIView communication with UIViewController

开发者 https://www.devze.com 2023-03-16 00:26 出处:网络
From within a UIViewController, I programmatically create about 10 instances of a CustomUIView and place them on the [UIViewController view].

From within a UIViewController, I programmatically create about 10 instances of a CustomUIView and place them on the [UIViewController view].

When any of those instances of CustomUIView is touched, I want to let the controller know and take some action.

I've thought of two ways to do this:

  1. Subscribe the UIViewController as an observer to the CustomUIView. Then when touchesBegan:withEvent: is fired, call a method on the UIViewController observer.

  2. 开发者_如何学Python

    Use [self.nextResponder touchesBegan:touches withEvent:event] to raise the event to the UIViewController.

I've implemented both, and they both work ok.

Question: What is the best way for a programmatically-created view to communicate with its UIViewController? Is one of these the way to go? Or is there a third way?

The resources I've found online are very good at explaining all the Cocoa "pieces", but I'm having trouble finding best practices for overall architecture.


For the case of touch events, you don't have to do anything!

From the UIViewController class reference:

View controllers are tightly bound to the views they manage and take part in the responder chain used to handle events. View controllers are themselves descendants of the UIResponder class and are inserted into the responder chain between the managed root view and its superview, which typically belongs to a different view controller. If the view controller’s view does not handle an event, the view controller itself has the option of handling the event before passing the event along to the superview.

This means your view controller can handle touch events in its view without any extra setup, as long as you don't handle them in your view.


You would make the UIViewController the delegate for the UIViews, if you want the views to be able to communicate back to the controller.

Touch events will automatically get sent to the Controller as part of the responder chain.

0

精彩评论

暂无评论...
验证码 换一张
取 消