简体   繁体   中英

Parse UIButton into method in Objective-C

I have some methods that interact with the UIButtons in my view controller, with a lot of repetitive code. Here's an example of one of those methods:

-(void)spinButtons {
CABasicAnimation *fullRotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
fullRotation.fromValue = [NSNumber numberWithFloat:0];
fullRotation.toValue = [NSNumber numberWithFloat:((360*M_PI)/180)];
fullRotation.duration = 3;
fullRotation.repeatCount = 0;


[_button1.layer addAnimation:fullRotation forKey:@"360"];
[_button2.layer addAnimation:fullRotation forKey:@"360"];
[_button3.layer addAnimation:fullRotation forKey:@"360"];
[_button4.layer addAnimation:fullRotation forKey:@"360"];
[_button5.layer addAnimation:fullRotation forKey:@"360"];
[_button6.layer addAnimation:fullRotation forKey:@"360"];

}

Is there a way how I can store the name of the buttons in an NSdictionary, list etc so i can turn the above into this:

-(void)spinButtons:(UIButton *)button {
CABasicAnimation *fullRotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
fullRotation.fromValue = [NSNumber numberWithFloat:0];
fullRotation.toValue = [NSNumber numberWithFloat:((360*M_PI)/180)];
fullRotation.duration = 3;
fullRotation.repeatCount = 0;

[button.layer addAnimation:fullRotation forKey:@"360"];

}

I Hope this makes sense!

If you're using Interface Builder, you could construct an IBOutletCollection to which you would add all of your buttons.

As far as I know, this isn't ordered, so if order is important to you, you might have to find a different way.

You can use KVC .

[[self valueForKeyPath:"button1.layer"] addAnimation:fullRotation forKey:@"360"];

So for the array

NSArray *layers = @["button1.layer", "button2.layer", "button3.layer", "button4.layer", "button5.layer", "button6.layer"];
for (NSString *layer in layers) {
    [[self valueForKeyPath:layer] addAnimation:fullRotation forKey:@"360"];
}

UPDATE

To set a value with KVC, you can use -setValue:forKeyPath: .

For example, to set a button:

[self setValue:[UIButton buttonWithType:UIButtonTypeSystem] forKeyPath:"button1"];

Things get more complex for non-object types: these get wrapped in objects like NSValue and NSNumber . For example, a button1.frame is a CGRect … which is a struct . CGRect s are placed in NSValue wrappers.

Here is using KVC to get a frame.

CGRect frame = [[self valueForKeyPath:"button1.frame"] CGRectValue];

The same thing must be done when using -setValue:forKeyPath: .

CGRect frame = CGRectMake(0.0, 0.0, 0.0, 0.0);
[self setValue:[NSValue valueWithCGRect:frame] forKeyPath:"button1.frame"];

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