建立一個界面,就像這樣的:swift
頂部是一個UISegmentControl,用來制定transform的類型。分別是:CGAffineTransformMakeTranslation、CGAffineTransformTranslate、CGAffineTransformIdentity.
ide
而後是一個UILabel,這個Label實時的顯示當前的動畫類型是什麼。動畫
桔色的是動畫的View。spa
最下面是一個按鈕,按這個按鈕桔色的View開始執行動畫。code
其餘的,藍色的線就是這幾個View的Constraints。指定這幾個view的定位是如何的,好比,相對於頂部的距離,相對於左邊的距離,右邊的距離等。orm
配置好頁面上的View以後,給這些View在Controller中指定對應的對象。並在nib文件中指定各個View的事件。對象
View在controller中對應的對象:blog
@IBOutlet weak var animationView: UIView! @IBOutlet weak var animationLabel: UILabel!
UISegmentControl的事件:事件
@IBAction func segmentAction(sender: AnyObject) { var segmentControl = sender as UISegmentedControl animationType = segmentControl.selectedSegmentIndex }
運行動畫的按鈕的事件:animation
@IBAction func runAction(sender: AnyObject) { var distance: CGFloat = 30 switch animationType { case 0: self.animationLabel.text = "CGAffineTransformMakeTranslation" UIView.animateWithDuration(1.0, animations: { self.animationView.transform = CGAffineTransformMakeTranslation(distance, 0) }) case 1: self.animationLabel.text = "CGAffineTransformTranslate" UIView.animateWithDuration(1.0, animations: { self.animationView.transform = CGAffineTransformTranslate(self.animationView.transform, distance, 0) }) case 2: self.animationLabel.text = "CGAffineTransformIdentity" UIView.animateWithDuration(1.0, animations: { self.animationView.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, distance, 0) }) default: println("") } }
在ViewDidLoad設置選擇的動畫的類型,這裏咱們不直接取UISegmentControl的selectedIndex的值。因此,在ViewDidLoad方法內設定默認值是1(即選定到是第一個)。
所有代碼:
// // ViewController.swift // TransformDemo // // Created by Bruce Lee on 30/11/14. // Copyright (c) 2014 Dynamic Cell. All rights reserved. // // QQ:1828099940, 羣:58099570 歡迎加入討論 // import UIKit class ViewController: UIViewController { @IBOutlet weak var animationView: UIView! @IBOutlet weak var animationLabel: UILabel! var animationType: Int! override func viewDidLoad() { super.viewDidLoad() animationType = 0 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func segmentAction(sender: AnyObject) { var segmentControl = sender as UISegmentedControl animationType = segmentControl.selectedSegmentIndex } @IBAction func runAction(sender: AnyObject) { var distance: CGFloat = 30 switch animationType { case 0: self.animationLabel.text = "CGAffineTransformMakeTranslation" UIView.animateWithDuration(1.0, animations: { self.animationView.transform = CGAffineTransformMakeTranslation(distance, 0) }) case 1: self.animationLabel.text = "CGAffineTransformTranslate" UIView.animateWithDuration(1.0, animations: { self.animationView.transform = CGAffineTransformTranslate(self.animationView.transform, distance, 0) }) case 2: self.animationLabel.text = "CGAffineTransformIdentity" UIView.animateWithDuration(1.0, animations: { self.animationView.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, distance, 0) }) default: println("") } } }