簡體   English   中英

iOS UIButton 縮放動畫

[英]iOS UIButton scale animation

我正在處理一個 UIButton 動畫,它沿着 x 軸移動,同時從初始大小縮放到其原始大小。 當我嘗試下面的代碼時,它不會移動到它應該去的地方,也不會放大到其原始大小。

這是我初始化按鈕的代碼:

 _testBtn1.layer.anchorPoint = CGPointMake(0.5f, 0.5f);
scaleBtn = CGAffineTransformMakeScale(0.2, 0.2);
[_testBtn1 setTransform: scaleBtn];

這是我的移動/平移和縮放代碼:

CGAffineTransform translate = CGAffineTransformMakeTranslation(50.0f, 0.0f);
CGAffineTransform animate = CGAffineTransformConcat(scaleBtn, translate);
[_testBtn1 setTransform:animate];

任何幫助,建議,意見將不勝感激。 我是 iOS 新手……謝謝!

您可以創建一個自定義類型的 UIButton(使用 IB 通過將類型更改為自定義,或以編程方式使用

UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];//set the button's image with 
[aButton setImage:[UIImage imageNamed:@"abc" forState:UIControlStateNormal];

要移動它,只需正常設置其位置的動畫...

[UIView animateWithDuration:0.5 animations:^{aButton.center = newCenter;}];

要么

CGRect originalFrame = aButton.frame;
aButton.frame = CGRectMake(originalFrame.origin.x, originalFrame.origin.y, originalFrame.size.width, 0);
[UIView animateWithDuration:0.5 animations:^{aButton.frame = originalFrame;}];

或參考此鏈接http://objectiveapple.blogspot.in/2011/10/23-quizapp-16-animate-scale-uibutton.html

這應該很容易用 Core Animation 完成,看看最基礎的一個CABasicAnimation

一個簡單的縮放(有彈性)動畫,在 swift 中完成處理程序實現。

希望它會以某種方式幫助您或其他任何人。

viewToanimate.transform = CGAffineTransform(scaleX: 0.1, y: 0.1) UIView.animate(withDuration: 0.7, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 6.0, animations: { _ in viewToAnimate.transform = .identity }, completion: { _ in //Implement your awesome logic here. })

我做了這個動畫:

在此處輸入圖片說明

有了這個可重用的類:

class AnimatedButton: UIButton {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addTargets()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        addTargets()
    }
    
    func addTargets() {
        self.addTarget(self, action: #selector(scaleDownAnimated), for: .touchDown)
        self.addTarget(self, action: #selector(scaleBackToNormalAnimated), for: [.touchUpOutside, .touchCancel, .touchUpInside])
    }
    
    @objc func scaleDownAnimated() {
        UIView.animate(withDuration: 0.25, delay: 0, options: .allowUserInteraction) {
            self.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
        } completion: { _ in }
    }
    
    @objc func scaleBackToNormalAnimated() {
        UIView.animate(withDuration: 0.2, delay: 0, options: .allowUserInteraction) {
            self.transform = CGAffineTransform(scaleX: 1, y: 1)
        } completion: { _ in }
    }
}

然后只需將按鈕的類AnimatedButton如下所示(如果您使用的是 Storyboards)並正常使用按鈕:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM