For iOS development, if you create and add a sub view at runtime, how would you allow it to communicate with the view controller? Since the sub view isn't instantiated within a nib, you can't use Interface Builder to drag a开发者_JAVA百科 connection to an IBAction
method on the controller. I can't see an obvious way to grab a handle to the controller from the view. Or am I looking at it the wrong way and should instead be communicating with it indirectly via NSNotificationCenter
?
Most views don't communicate directly with the view controller. Rather, they are connected to an IBOutlet, or they use target-action to call a method on the view controller.
For the former, just declare an IBOutlet property as you normally would and set it after you create the view. (Note that technically, you don't need the IBOutlet keyword as you're not making a connection in IB, but I don't think it hurts anything.)
self.myViewOutlet = myNewView;
If your UIView is a subclass of UIControl, use addTarget: action: forControlEvents: to have methods of your view controller called when certain events happen on the control.
[myNewControl addTarget:self action:@selector(mySelector:) forControlEvents:UIControlEventTouchDragInside];
What are you trying to communicate? IBActions are for predifined (or newly defined if you want to go through the hassle of adding ur UI element to IB) UI elements that can trigger some selector upon some interaction, for that you can always have the same effect programatically... For example, to create a UIButton at run time you can do..
UIButton *button=[[UIButton alloc] initWithFrame:frame];
[button addTarget:self action:@selector(myAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
Anything that you can do in interface builder you can do programatically as well...you just have to look for the methods that will bind actions to the UI element ...hope this helps.
After reading your comment: You can consider creating the buttons from the view controller instead of the view, probably the might be the correct way to do it (dont know your circumstance though)...If not then either the view can handle your events and use a protocol to delegate the events to the view controller, or you can use a protocol to register as a target to the UI element, there are many ways to go about solving your problem, what are your circumstances?
Answering it myself... I was creating these subviews from within a parent view so didn't have access to the controller there either, so the self
in the code examples from the other answers wasn't possible. But then after thinking about it a bit, I've decided to move the code into the controller itself but instead chose to use a delegate rather than a target-action because it's a custom message, not just a simple touch event. Thanks to those who helped.
精彩评论