Text Size
Monday, June 18, 2018


get object with tag like button or image

Once you have created an object unless you created a property for it, it can be hard to access the object, like changing an image or changing the pressed method to call for a button, here is how you do it:

First assign a tag to the object when you create it, a tag is simply a number is can be positive or negative:

    UIButton *buttonBegin = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonBegin.frame = CGRectMake(100, (self.view.bounds.size.height - 120) /2 , 120, 120);
    buttonBegin.tag = -2;
    [buttonBegin setImage:[UIImage imageNamed:@"splat1.png"] forState:UIControlStateNormal];
    [buttonBegin addTarget:self action:@selector(buttonBeginPressed:) forControlEvents:UIControlEventTouchUpInside];

How later in the code I wan to cancel the target or change the image for example:

    UIButton *buttonNext =( (UIButton *) [self.view viewWithTag:-2]); // is the same as button Begin ( just using a pointer )
    // Remove the action
    [buttonNext removeTarget:self action:@selector(buttonBeginPressed:)  forControlEvents:UIControlEventTouchUpInside];
    // Add a new action
    [buttonNext addTarget:self action:@selector(buttonNextPressed:) forControlEvents:UIControlEventTouchUpInside];
    // Change the image
    [buttonBegin setImage:[UIImage imageNamed:@"splat2.png"] forState:UIControlStateNormal];

What to remember is : UIButton *buttonNext =( (UIButton *) [self.view viewWithTag:-2]);

You can do this for any object : UIImageView *imageExample =( (UIImageView *) [self.view viewWithTag:23]);

You can use 'id' if you do not know what type of object it is, but is it better to get the correct type of object so the auto complete comes up.

Copyright © 2018 by Mike Zriel - Zriel.com