简体   繁体   中英

iOS: setting alphas of multiple buttons at once

Okay, so I don't really know if NSDictionary is the correct approach to this, but I am using a fade animation to take different groups of buttons on and off a screen. I want to "compartmentalize" them, so to speak, into different groups so I can do this in one or two lines without having to rewrite all the buttons names every time (there are a good amount). Any ideas on how to do this?

[UIView animateWithDuration: 1.5
        animations: ^(void)
        {
            //As an example i just called them button1, button2, etc.
            self.button1.alpha = 1;
            self.button2.alpha = 1;
            self.button3.alpha = 1;
            self.button4.alpha = 1;
            self.button5.alpha = 1;
        }
 ];

I included the above as an example of what I am asking. Is there a way to put all the buttons in an NSDictionary and write one line (where the buttons are currently located) that changes all of their alphas?

The preferred mechanism nowadays for buttons you've added in Interface Builder would be an IBOutletCollection :

@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *buttons;

展示挂钩收集

Clearly, in Interface Builder you would connect the individual buttons to the outlet collection. For a discussion of IBOutletCollection , see NSHipster's IBAction / IBOutlet / IBOutlet​Collection article.

If you're not using Interface Builder, but rather have created these buttons programmatically, you could just have an NSArray :

@property (strong, nonatomic) NSArray *buttons;

Which you'd then populate yourself:

self.buttons = @[self.button1, self.button2, self.button3, self.button4, self.button5, self.button6];

Regardless of how you build this array (either outlet collection or manually populated), you can then iterate through that array as you update a property of the buttons:

for (UIButton *button in self.buttons) {
    button.alpha = 1;
}

Or, even simpler, you can update all of them with setValue:forKey: :

[self.buttons setValue:@1 forKey:@"alpha"];

You can use button tags to accomplish this. Set the same tag for multiple buttons (your groups) and do:

button.tag = 1;

then:

for (UIButton *btn in button) {
    if(btn.tag == 1)
    {
        // do something
        break; // don't need to run the rest of the loop
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM