我想在按钮上添加动画,使按钮将A点移到B点
以下代码可以做到。但奇怪的是,当按钮移动时,它无法再检测到触摸。
如果您点击按钮的原始位置,它可以触发按钮事件。我的代码中是否有任何遗漏?
请帮帮我。
- (IBAction)button:(id)sender
{
UIButton *lineButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[lineButton addTarget:self action:@selector(press:)forControlEvents:UIControlEventTouchUpInside];
[lineButton setFrame:CGRectMake(50, 50, 50, 50)];
[self.view addSubview:lineButton];
CABasicAnimation *lineAnimation;
lineAnimation = [CABasicAnimation animationWithKeyPath:@"position"];
[lineAnimation setRemovedOnCompletion:NO];
[lineAnimation setDuration:0.15];
[lineAnimation setFillMode:kCAFillModeForwards];
[lineAnimation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]];
CGRect rect = CGRectMake(100, 200, 50, 50);
lineAnimation.fromValue = [NSValue valueWithCGPoint: CGPointMake(50, 50)];
lineAnimation.toValue = [NSValue valueWithCGPoint:CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect))];
[lineAnimation setAutoreverses:NO];
[lineButton.layer addAnimation:lineAnimation forKey:@"line"];
}
答案 0 :(得分:2)
您必须在addAnimation方法之后将新框架和图层设置为按钮的框架/图层,如:
lineButton.frame = rect
lineButton.layer.frame = rect
或者你可以简单地使用动画块(更容易使用,代码看起来不错等等),例如:
[UIView animateWithDuration:0.15 animations:^{
lineButton.frame = CGRectMake(100, 200, 50, 50);
}];
答案 1 :(得分:0)
在您的界面构建器中,在按钮和设置框架上正确设置自动调整属性。如果旋转设备或模拟器,则会自动进行帧大小调整。然后你将失去原始框架。