【发布时间】:2014-10-09 08:19:47
【问题描述】:
我正在尝试编写一个自定义的UIButton 子类,它将在新闻发布期间“动画化”。
按下时,按钮应“缩小”(朝向其中心)至其原始大小的 90%。 释放后,按钮应“展开”到 105%,再次缩小到 95%,然后恢复到原来的大小。
这是我现在得到的代码:
#pragma mark -
#pragma mark - Touch Handling
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesBegan:touches withEvent:event];
[self animatePressedDown];
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesCancelled:touches withEvent:event];
[self animateReleased];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesEnded:touches withEvent:event];
[self animateReleased];
}
- (void)animatePressedDown {
NSLog(@"button.frame before animatedPressedDown: %@", NSStringFromCGRect(self.frame));
[self addShadowLayer];
CATransform3D ninetyPercent = CATransform3DMakeScale(0.90f, 0.90f, 1.00f);
[UIView animateWithDuration:0.2f
animations:^{
self.layer.transform = ninetyPercent;
}
completion:^(BOOL finished) {
NSLog(@"button.frame after animatedPressedDown: %@", NSStringFromCGRect(self.frame));
}
];
}
- (void)animateReleased {
[self.shadowLayer removeFromSuperlayer];
CATransform3D oneHundredFivePercent = CATransform3DMakeScale(1.05f, 1.05f, 1.00f);
CATransform3D ninetyFivePercent = CATransform3DMakeScale(0.95f, 0.95f, 1.00f);
[UIView animateWithDuration:0.1f
animations:^{
self.layer.transform = oneHundredFivePercent;
}
completion:^(BOOL finished) {
NSLog(@"button.frame after animateReleased (Stage 1): %@", NSStringFromCGRect(self.frame));
[UIView animateWithDuration:0.1f
animations:^{
self.layer.transform = ninetyFivePercent;
}
completion:^(BOOL finished) {
NSLog(@"button.frame after animateReleased (Stage 2): %@", NSStringFromCGRect(self.frame));
[UIView animateWithDuration:0.1f
animations:^{
self.layer.transform = CATransform3DIdentity;
self.layer.frame = self.frame;
}
completion:^(BOOL finished) {
NSLog(@"button.frame after animateReleased (Stage 3): %@", NSStringFromCGRect(self.frame));
}
];
}
];
}
];
}
无论如何,上面的代码可以完美运行……有时。在其他时候,按钮动画按预期工作,但在“释放”动画之后,按钮的最后一帧从其原始位置向上和向左“移动”。这就是为什么我有那些NSLog 语句,以准确跟踪动画每个阶段按钮框架的位置。当“转变”发生时,它发生在animatePressedDown 和animateReleased 之间。至少,animatePressedDown 中显示的框架是 ALWAYS 我所期望的,但animateReleased 中框架的第一个值经常出错。
我看不出这种疯狂的模式,尽管我的应用程序中的相同按钮在不同应用程序运行之间往往表现得正确或不正确。
我对所有按钮都使用了自动布局,所以我不知道让一个按钮正常工作而另一个按钮改变其位置有什么区别。
【问题讨论】:
标签: ios objective-c animation uibutton