我看不出我的代码有什么问题。当我按下按钮时没有任何反应,就好像默认状态甚至没有设置一样,这很奇怪,因为playButton.state = UIControlStateNormal
属性是只读的,我们无法执行state
。
这是我的代码:
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
// ...
playButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
playButton.frame = CGRectMake(100, 500, 100, 50);
[playButton setTitle:@"play" forState: UIControlStateNormal];
[playButton setTitle:@"stop" forState: UIControlStateSelected];
playButton.exclusiveTouch = YES;
playButton.selected = NO;
[playButton addTarget:self action:@selector(play) forControlEvents:UIControlEventTouchUpInside];
和
- (void) play {
if (playButton.state == UIControlStateNormal) {
playButton.selected = YES;
CABasicAnimation *maskAnim = [CABasicAnimation animationWithKeyPath:@"position.x"];
maskAnim.byValue = [NSNumber numberWithFloat:diagramWidth];
maskAnim.repeatCount = HUGE_VALF;
maskAnim.duration = 1.750f;
[self.maskLayer addAnimation:maskAnim forKey:@"position.x"];
self.diagramLayer.mask = maskLayer;
[backImageLayer addSublayer: self.diagramLayer];
[audioPlayerNormal play];
[moviePlayerNormal play];
}
else if (playButton.state == UIControlStateSelected) {
playButton.selected = NO;
[self.maskLayer removeAnimationForKey:@"position.x"];
self.diagramLayer.mask = nil;
[audioPlayerNormal stop];
[moviePlayerNormal stop];
}
}
答案 0 :(得分:2)
以下代码应该可以胜任。
- (void) play {
if (playButton.selected == NO) {
CABasicAnimation *maskAnim = [CABasicAnimation animationWithKeyPath:@"position.x"];
maskAnim.byValue = [NSNumber numberWithFloat:diagramWidth];
maskAnim.repeatCount = HUGE_VALF;
maskAnim.duration = 1.750f;
[self.maskLayer addAnimation:maskAnim forKey:@"position.x"];
self.diagramLayer.mask = maskLayer;
[backImageLayer addSublayer: self.diagramLayer];
[audioPlayerNormal play];
[moviePlayerNormal play];
}
else {
[self.maskLayer removeAnimationForKey:@"position.x"];
self.diagramLayer.mask = nil;
[audioPlayerNormal stop];
[moviePlayerNormal stop];
}
playButton.selected = !playButton.selected;
}