3

我想给一个按钮添加一个动画,使按钮从 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"];
}
4

2 回答 2

2

您必须在 addAnimation 方法之后将新框架和图层设置为按钮的框架/图层,例如:

lineButton.frame = rect
lineButton.layer.frame = rect

或者您可以简单地使用动画块(更易于使用,代码看起来不错等),例如:

[UIView animateWithDuration:0.15 animations:^{
  lineButton.frame = CGRectMake(100, 200, 50, 50);
}];
于 2012-07-18T12:23:06.477 回答
0

在您的 interfacebuilder 中正确设置按钮和 setframes 的 autoresizing 属性。如果您旋转设备或模拟器,则会自动调整帧大小。然后你会失去原来的框架。

于 2012-07-18T12:08:31.293 回答