繁体   English   中英

将UIButton解析为Objective-C中的方法

[英]Parse UIButton into method in Objective-C

我有一些与视图控制器中的UIButton交互的方法,其中包含很多重复的代码。 这是其中一种方法的示例:

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

}

有没有一种方法可以将按钮的名称存储在NSdictionary,列表等中,因此我可以将以上内容转换为:

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

}

我希望这是有道理的!

如果使用的是Interface Builder,则可以构造一个IBOutletCollection向其中添加所有按钮。

据我所知,这是没有顺序的,因此,如果顺序对您很重要,则可能必须找到其他方法。

您可以使用KVC

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

所以对于数组

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

更新

要使用KVC设置值,可以使用-setValue:forKeyPath:

例如,要设置一个按钮:

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

对于非对象类型,事情变得更加复杂:它们被包裹在NSValueNSNumber类的对象中。 例如, button1.frameCGRect …是struct CGRect放置在NSValue包装器中。

这是使用KVC获取框架。

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

使用-setValue:forKeyPath:时必须完成相同的操作。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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