vinylDeveloper
vinylDeveloper

Reputation: 707

How do I access a button in a subview

I want to implement this fade in/out in a horizontal scroll I have, but I can't figure out how to access my button that is in a subview of my UIScrollView. This is what I'm trying to implement Fade in/out stackoverflow.

This is my code...

        Game *game = (Game *)[_schedule.games objectAtIndex:i];
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x, 20, 150, 100)];
        [button setBackgroundImage:[UIImage imageNamed:game.opponent] forState:UIControlStateNormal];
        //[button setTitle:game.opponent forState:UIControlStateNormal];
        [_gameScrollList addSubview:button];

How Can I add the observer to my button, Can this be done?

        [self.scrollView addObserver:[self.contentViews objectAtIndex:i] 
                          forKeyPath:@"contentOffset" 
                             options:NSKeyValueObservingOptionNew
                             context:@selector(updateAlpha:)];

Upvotes: 0

Views: 651

Answers (1)

Lucas Eduardo
Lucas Eduardo

Reputation: 11675

To access the reference of this button added as subview, you can:

  • Use this button as a iVar, saving the reference to use it later;

  • Similarly, use this button as a property;

  • Iterate through subviews of _gameScrollList, looking for a subview of UIButton's class (not recommended, will work well only if it has just one UIButton as subview)

Example of how implement the second approach. Just declare a property:

@property(nonatomic, strong) UIButton *button;

and then:

    Game *game = (Game *)[_schedule.games objectAtIndex:i];
    self.button = [[UIButton alloc] initWithFrame:CGRectMake(x, 20, 150, 100)];
    [self.button setBackgroundImage:[UIImage imageNamed:game.opponent] forState:UIControlStateNormal];
    //[self.button setTitle:game.opponent forState:UIControlStateNormal];
    [_gameScrollList addSubview:self.button];

So, after, when you want to access this button somewhere, just call for the property

self.button.alpha = 0.5; //example of interation with your button

If this is not what you are looking for, you really should edit your question to be more clear.

Hope it helped.

Upvotes: 1

Related Questions