iOS: setting alphas of multiple buttons at once

£可爱£侵袭症+ 提交于 2019-12-11 03:02:47

问题


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?


回答1:


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"];



回答2:


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
    }
}


来源:https://stackoverflow.com/questions/31729369/ios-setting-alphas-of-multiple-buttons-at-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!