请问如何在触摸时缩放 UIButton
?按钮应该放大约 10%。
提前感谢!
调用
button.transform = CGAffineTransformMakeScale(1.1,1.1);
在按钮按下的处理程序中。
或者如果你想要带有动画效果的缩放:
[UIView beginAnimations:@"ScaleButton" context:NULL];
[UIView setAnimationDuration: 0.5f];
button.transform = CGAffineTransformMakeScale(1.1,1.1);
[UIView commitAnimations];
// Scale up on button press
- (void) buttonPress:(UIButton*)button {
button.transform = CGAffineTransformMakeScale(1.1, 1.1);
// Do something else
}
// Scale down on button release
- (void) buttonRelease:(UIButton*)button {
button.transform = CGAffineTransformMakeScale(1.0, 1.0);
// Do something else
}
然后通过以下方式与按钮的事件相连:
[btn addTarget:self action:@selector(buttonPress:) forControlEvents:UIControlEventTouchDown];
[btn addTarget:self action:@selector(buttonRelease:) forControlEvents:UIControlEventTouchUpInside];
[btn addTarget:self action:@selector(buttonRelease:) forControlEvents:UIControlEventTouchUpOutside];
注意1:将CGAffineTransformMakeScale值设置为1.0不能保持它们的更改值(即它不会将1.1乘以1.0),而是将其设置回对象的原始比例。
注意2:不要忘记选择器中的冒号:
,因为它允许将发送者作为参数传递给接收方法。在这种情况下,我们的方法接收一个UIButton,并在接口(.h文件)中声明为这样。
UIControlEventTouchCancel
和 UIControlEventTouchDragExit
。 - Tim为了使它更像本地的 UIButton 行为,我更喜欢在子类中使用 touchesBegan
和 touchesEnded
方法:
class BaseButton: UIButton {
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
UIView.animate(withDuration: 0.3) {
self.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
self.titleLabel?.alpha = 0.7
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
UIView.animate(withDuration: 0.3) {
self.transform = .identity
self.titleLabel?.alpha = 1
}
}
}
在你的故事板中,让你的按钮继承自 BaseButton
类。
- (IBAction) buttonTapAction:(UIButton *) sender {
[self animatePressedDown:sender duration:0.6 zoom:1.5];
}
- (void)animatePressedDown:(UIButton *) sender duration:(double) t zoom:(double) zoomX {
[UIView animateWithDuration:t delay:0.0 options:UIViewAnimationOptionCurveEaseOut animations:^{
sender.transform = CGAffineTransformMakeScale(zoomX,zoomX);
} completion:^(BOOL finished) {
[UIView animateWithDuration:t delay:0.0 options:UIViewAnimationOptionCurveEaseOut animations:^{
sender.transform = CGAffineTransformMakeScale(1,1);
} completion:nil];
}];
}
这是我使用的东西
-(IBAction)heartButtonTapped:(UIButton*)sender {
[sender setSelected:!sender.isSelected];
[UIView animateWithDuration:0.6 delay:0.0 options:UIViewAnimationOptionAutoreverse animations:^{
sender.transform = CGAffineTransformMakeScale(1.5,1.5);
} completion:^(BOOL finished) {
sender.transform = CGAffineTransformMakeScale(1,1);
}];
}
Swift:
button.transform = CGAffineTransform.init(scaleX: 1.0, y: 1.0)
Swift 5:
@objc func onProfileClick(_ sender: CTCircularButton) {
UIView.animate(withDuration: 0.5, animations: {
sender.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
}) { (isComplete) in
UIView.animate(withDuration: 0.5) {
sender.transform = .identity
}
print("Your action here")
}
}