Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone: calling a parent/super method from a subview

hope someone can help me on this as been stuck for hours.

I am trying to make a kind of picture book. I have a view which is my container and I add subviews to that by using addsubview.

On the subview, I have swipe gestures etc that I want to trigger off method in the parent view. I worked out how to trigger the delegate but I cant get the delegate to trigger the parent view. I have read over 10 different ways of doing it and none work.

I now very confused about what a super view is to. Just to confuse matters, the delegate has a tabcontroller and the parent view is tab button 1

I tried

[self.view.superview method]
[self.superview method]

On the delegate I tried self.tabcontroller.parentviewcontroller, selectedview, super view.super

UPDATE : The subview needs to be independant of the parent view as its a reusable view. Also I have not set the parentview to superview as I just thought a superview is a view with subviews (please don't kill me). So maybe I just need to set the parentview to a superview?

like image 650
Burf2000 Avatar asked Sep 22 '10 15:09

Burf2000


2 Answers

The proper way of doing such things is to use protocol and delegate pattern.

Define a protocol like

@protocol subViewDelegate
   -(void)somethingHappened:(id)sender;
@end

then implement that protocol in your superview :

@interface superView:UIViewController<subViewDelegate> {
...
}
...
@end

define a delegate property in your SubView like this

@interface subView : UIView {
   id<subViewDelegate> delegate;
   ...
}
@propery (nonatomic, assign) id<subViewDelegate> delegate;
...
@end

the in your subview, call the delegate like this

[self.delegate somethingHappened :self];
like image 183
VdesmedT Avatar answered Nov 15 '22 13:11

VdesmedT


It's a little hard to help you without any code given, but let's try:

  1. Create a protocol: Name it however you like (I will call it "MyProtocol") and add to it the definition of the function you want to call in your superview, let's call it "respondToSwipe"
  2. If your superview is a UIView, you have to create your own subclass of UIView and make your superview an instance of that class.
  3. Let your (newly) created superview class implement the protocol of 1.) an implement the "respondToSwipe" method
  4. Create an instance variable of the the type id in your subview, and name it however you like, e.g. "myDelegate".
  5. Pass the superview created in 2/3.) to your "myDelegate" variable
  6. Call [myDelegate respondToSwipe] whenever you like
like image 44
Philipp Schlösser Avatar answered Nov 15 '22 13:11

Philipp Schlösser