Saya mencoba membuat animasi gradien sehingga lokasi dua warna bergeser dari kiri ke kanan. Masalahnya adalah setelah animasi selesai, lokasi gradien kembali ke posisi semula.

Ini kode taman bermain saya:

import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {

  let gradientLayer: CAGradientLayer = {
    let layer = CAGradientLayer()
    layer.colors = [ UIColor.red.cgColor, UIColor.blue.cgColor ]
    layer.locations = [0.0, 0.5]
    layer.startPoint = CGPoint(x: 0.0, y: 1.0)
    layer.endPoint = CGPoint(x: 1.0, y: 1.0)

    return layer
  }()

  override func viewDidLoad() {
    super.viewDidLoad()

    view.layer.addSublayer(gradientLayer)
    gradientLayer.frame = view.bounds

    let gradientChangeAnimation = CABasicAnimation(keyPath: "locations")
    gradientChangeAnimation.duration = 1
    gradientChangeAnimation.toValue = [0.5, 1.0]
    gradientLayer.add(gradientChangeAnimation, forKey: nil)

  }

  override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    gradientLayer.frame = view.frame
  }
}

// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()

Bagaimana cara mencegah pengaturan ulang lokasi setelah animasi selesai?

0
Scott Kaiser 27 Desember 2017, 23:02

1 menjawab

Jawaban Terbaik

Anda bisa memintanya untuk tidak menghapus saat selesai dan mengatur lokasi ke nilai baru:

override func viewDidLoad() {
    super.viewDidLoad()

    view.layer.addSublayer(gradientLayer)
    gradientLayer.frame = view.bounds

    CATransaction.begin()
    CATransaction. setCompletionBlock {
        gradientLayer.locations = [0.5, 1.0]
        gradientLayer.removeAllAnimations()
    }

    let gradientChangeAnimation = CABasicAnimation(keyPath: "locations")
    gradientChangeAnimation.duration = 1
    gradientChangeAnimation.toValue = [0.5, 1.0]
    gradientLayer.add(gradientChangeAnimation, forKey: nil)

    CATransaction.commit()
}

Atau setel properti fillMode dan isRemovedOnCompletion dengan tepat.

override func viewDidLoad() {
    super.viewDidLoad()

    view.layer.addSublayer(gradientLayer)
    gradientLayer.frame = view.bounds

    let gradientChangeAnimation = CABasicAnimation(keyPath: "locations")
    gradientChangeAnimation.duration = 1
    gradientChangeAnimation.toValue = [0.5, 1.0]
    gradientChangeAnimation.fillMode = kCAFillModeForwards
    gradientChangeAnimation.isRemovedOnCompletion = false
    gradientLayer.add(gradientChangeAnimation, forKey: nil)
}
1
Scott Kaiser 2 Januari 2018, 20:49