其實 iOS 原生有提供一些設計好的轉場動畫,比如簡單的翻轉效果,這次把原生的轉場效果都看一次。
Transitions
共有七種 UIView Transition 效果,底下 0~6 是用來切換效果的,點下按鈕 GO 的時候就會執行動畫。
ContainerView
通過 setupView 我們建立 containerView / owlImageView / catImageView 並設定他們的樣式(比如圓角)
然後將 containerView 放在 ViewController 的 view 上,將 owlImageView 放在 containerView 上。
而 catImageView 並沒有成為其他 View 的 SubView 而是後面做轉場動畫的時候會被替換。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
fileprivate func setupView() { let screen = UIScreen.main.bounds goButton.layer.cornerRadius = 22 let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 250, height: 250)) containerView.backgroundColor = UIColor(red: 6/255, green: 111/255, blue: 165/255, alpha: 1.0) containerView.layer.borderColor = UIColor.white.cgColor containerView.layer.borderWidth = 2 containerView.layer.cornerRadius = 20 containerView.center = CGPoint(x: screen.midX, y: screen.midY) view.addSubview(containerView) catImageView.frame.size = CGSize(width: 100, height: 100) catImageView.center = CGPoint(x: containerView.frame.width/2, y: containerView.frame.height/2) catImageView.layer.cornerRadius = 50 catImageView.clipsToBounds = true owlImageView.frame.size = CGSize(width: 100, height: 100) owlImageView.center = CGPoint(x: containerView.frame.width/2, y: containerView.frame.height/2) owlImageView.layer.cornerRadius = 50 owlImageView.clipsToBounds = true containerView.addSubview(owlImageView) } |
Transition
先判斷 segment 所選中的項目來選擇 UIViewAnimationOptions 然後通過 UIView.transition 來做轉場動畫。
這裡比較有趣的地方是,如果我們今天沒有 containerView 而是將內容都放在 ViewController 的 view 上,動畫效果就會很不一樣。
視覺上看起來有些動畫會帶動父視圖一起做,可以回到上面看這次的效果影片,會發現雖然是對 owlImageView 與 catImageView 切換做視圖轉場動畫,
但是 containerView 也一起跟著做動畫了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
fileprivate func doTransition() { let duration = 0.5 var option:UIViewAnimationOptions = .transitionCrossDissolve switch optionsSegment.selectedSegmentIndex { case 0: option = .transitionFlipFromLeft case 1: option = .transitionFlipFromRight case 2: option = .transitionCurlUp case 3: option = .transitionCurlDown case 4: option = .transitionCrossDissolve case 5: option = .transitionFlipFromTop case 6: option = .transitionFlipFromBottom default:break } if isReverseNeeded { UIView.transition(from: catImageView, to: owlImageView, duration: duration, options: option, completion: nil) } else { UIView.transition(from: owlImageView, to: catImageView, duration: duration, options: option, completion: nil) } isReverseNeeded = !isReverseNeeded } |
Reference
- 在 Github 上有本文相關的 Source Code