oskare
oskare

Reputation: 1061

Method call from subclass to view controller confusion

I have a method in my ViewController that adds an image view. The image view is in turn subclassed to be draggable. When touched, the subclass triggers a method (spawnImage) in ViewController to spawn a new image. If I call this method from within any other place in ViewController, the image is drawn correctly, however if the call originates from the subclass, the method gets called, the NSLog works but the image doesn't show up.

It seems like I'm creating another instance of ViewController in the subclass and end up adding the image to that one instead of in the one that is actually shown.

How could I solve this?

Subclass of UIImageView:

- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
…
ViewController *viewController = [[ViewController alloc] init];
[viewController checkIfImageIsInOriginalPosition:selfCenter letterIndex: imgTag];
}

ViewController.m:

-(void)checkIfImageIsInOriginalPosition:selfCenter letterIndex: imgTag {
…
else {
[self spawnImage];
}
}

-(void)spawnImage {
…
NSLog(@"Received");
SubClass *subClass = [[SubClass alloc] initWithFrame:frame];
[subClass setImage:image];
[self.view addSubview:subClass];
}

Upvotes: 1

Views: 218

Answers (1)

Duncan C
Duncan C

Reputation: 131511

This code:

- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
ViewController *viewController = [[ViewController alloc] init];
[viewController checkIfImageIsInOriginalPosition:selfCenter letterIndex: imgTag];
}

..is wrong.

presumably this is code inside Subclass, your subclass of UIImageView, and gets invoked when the user taps on it.

You should not alloc/init a new view controller. Instead, you should set up an "owningViewController" property in your SubClass UIImageView subclass, and set the property when you create an instance of SubClass:

-(void)spawnImage 
{
  …
  NSLog(@"Received");
  SubClass *subClass = [[SubClass alloc] initWithFrame:frame];
  owningViewController = self;
  [subClass setImage:image];
  [self.view addSubview:subClass];
}

Then your SubClass class's touchesBegan method would look like this:

- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event 
{
  …
  [self.owningViewController checkIfImageIsInOriginalPosition:selfCenter 
    letterIndex: imgTag];
}

Upvotes: 1

Related Questions