iOS專案開發實戰——配置自定義動畫

乞力馬紮羅的雪CYF發表於2015-08-19

       動畫很多的屬性,如位置,透明度等,開發者可以根據這些屬性來自定義自己需要的動畫。現在我們來簡單實現如何自定義動畫,以檢視的透明度的變化為例。其他的動畫效果可以參考我的其他兩篇部落格《iOS專案開發實戰——檢視動畫效果》《iOS專案開發實戰——實現檢視切換動畫》。

(1)同樣也在Images.xcassets中拖入一張圖片,然後在 Main.storyboard中使用一個ImageView控制元件來包含這張圖片。並且繫結控制元件到程式碼中。

(2)然後在ViewController中實現程式碼如下,我簡單實現了透明度迴圈改變的效果:

import UIKit

class ViewController: UIViewController {

    
    
    @IBOutlet weak var image: UIImageView!
    
    var isAlpha1:Bool = true
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.addSubview(image)
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        
        func anim1(){
        
            image.alpha = 0.5    //半透明;
            
        }
        
        func anim2(){
        
            image.alpha = 1.0    //不透明;
        }
        
        func complete(v:Bool){
        
            println("Complete")
            isAlpha1 = !isAlpha1   //迴圈改變透明度;
        }
        
        
        if(isAlpha1){
        
            UIView.transitionWithView(image, duration: 1.0, options: UIViewAnimationOptions.TransitionNone, animations: anim1, completion: complete)
        }else{
        UIView.transitionWithView(image, duration: 1.0, options: UIViewAnimationOptions.TransitionNone, animations: anim2, completion: complete)
            
        }
        
    }


}

(3)最後的實現效果如下:


.


github主頁:https://github.com/chenyufeng1991  。歡迎大家訪問!

相關文章