0
votes

For my iPad app, I am programmatically creating several UIImage views that I display on the screen. The code looks basically like this:

for(ModelObject *model in ModelsList){
    //create a UIImage view from the model object
    UIImageView *icon = [[UIImageView alloc] initWithFrame:model.icon_frame];
    icon.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:model.icon_path ofType:@"png"]];

     //add the imageview to a mutable array to keep track of them
    [myImageViews addObject:icon];

    // add the view as a subview
    [self.view addSubview:icon];
}

So now I have a bunch of icons displayed on the screen. But I would like to intercept touch events from the UIImageViews that I created programmatically, so that it calls some other method, preferably with an argument containing the sender's id or some other distinguishing information that I can use to determine which UIImageView was touched.

What is the best practices way of accomplishing this?

I am new to iOS so recommended reading would also be greatly appreciated.

1

1 Answers

0
votes

Please provide any applicable feedback, as I have no idea if this is common practice or even a decent way of doing things...

So basically what I did was keep a dictionary of ids that maps between the view object and the model objects, and then I look up the id of the sending view and find the appropriate model object, (I will then use that model object to load another view)

The code looks like this:

// in header
@property(nonatomic, retain) NSMutableDictionary *icons_to_models

// after creating a UIButton called icon
[icon setBackgroundImage:model.image forState:UIControlStateNormal];
[icon addTarget:self action:@selector(tappedIcon:) forControlEvents:UIControlEventTouchUpInside];
NSNumber *key = [NSNumber numberWithUnsignedInt:[icon hash]];
[icons_to_models setObject:model forKey:key];


...

//match sender to the icon that was pressed and
-(void)tappedIcon:(id)sender{
    NSNumber *key = [NSNumber numberWithUnsignedInt:[sender hash]];
    ModelObject *model = [icons_to_models objectForKey:key];
    NSLog(@"tapped on: %@", model.name);
}