Search code examples
iosobjective-cdelegatesuiimageviewpopover

iOS display image on a popover depending on the UIButton clicked


This is what I am trying to do:

screenshot

On clicking the 'info (i)' button I need to display a popover with an image on the left and some associated text to its right.

Now let's call the view in the background as 'View 1' and the popover as 'View 2'.

Here is what the View2Controller.h looks like:

@class View2Controller;
@protocol View2ControllerDelegate <NSObject>

- (void)infoPopover:(View2Controller *)obic loadImage: (NSString *)imageFilename;

@end

@interface View2Controller : UIViewController
@property (strong, nonatomic) IBOutlet UIImageView *imageInfo;
@property (strong, nonatomic) IBOutlet UILabel *textInfo;

@property (nonatomic, assign) id<View2ControllerDelegate> delegate;

@end

id <View2ControllerDelegate> _delegate;

Now the View1Controller.h has this line:

@interface View1Controller : UIViewController <View2ControllerDelegate>

And the @implementation of View1Controller.m looks somewhat like this

- (IBAction)showInfo:(id)sender {
UIButton *btn = (UIButton *)sender;

View2Controller *obic = [[View2Controller alloc]init];
[obic setDelegate:self];

switch (btn.tag) {
    case 1:
        [self infoPopover:obic loadImage:@"info1.png"];
        break;

    case 2:
        //Info View 2
        break;

    case 3:
        //Info View 3
        break;

    case 4:
        //Info View 4
        break;

    case 5:
        //Info View 5
        break;

    case 6:
        //Info View 6
        break;


    default:
        break;
}
}

and

- (void)infoPopover:(View2Controller *)obic loadImage:(NSString *)imageFilename
{
    [obic.imageInfo setImage:[UIImage imageNamed:imageFilename]];
}

I have looked up several tutorials on how delegates work. But i still can't display the image 'info1.png' on the 'UIImageView imageinfo'. Any comments are greatly appreciated!


Solution

  • SOLVED!!

    As suggested before by Paulw11 delegate was not the way to go in the first place. So I took the delegate code out. I also took out IBAction showinfo. Instead I used the method:

    -(BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender
    {
       if ([identifier isEqualToString:@"info"]) {
            UIButton *btn = (UIButton *)sender;
        [[NSUserDefaults standardUserDefaults]setInteger:btn.tag forKey:@"infoButton"];
    }
    return YES;
    

    in View1Controller and in the View2Controller I added :

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        NSArray *imageArray = @[@"info1.png", @"info2.png", @"info3.png", @"info4.png", @"info5.png", @"info6.png"];
        int infoButtonChoice = [[NSUserDefaults standardUserDefaults] integerForKey:@"infoButton"];
    
        [self.imageInfo setImage:[UIImage imageNamed:imageArray[infoButtonChoice -1]]];
    }
    

    and that makes the app work exactly as I want!!