只运行一次 CAEmitterLayer

Posted

技术标签:

【中文标题】只运行一次 CAEmitterLayer【英文标题】:Running CAEmitterLayer only once 【发布时间】:2018-04-18 22:22:17 【问题描述】:

我只想运行 CAEmitterLayer 一次,我想停止birthRate 但我做不到。我想要的是它在点击屏幕时只运行一次。我一直在与代表一起尝试,但我无法让它发挥作用。你能告诉我我的代码是否有效吗?

    import UIKit
    import PlaygroundSupport

    class Emitter 
        static func get(with image: UIImage) -> CAEmitterLayer 
            let emitter = CAEmitterLayer()
            emitter.emitterShape = kCAEmitterLayerLine
            emitter.emitterCells = generateEmitterCells(image: image)
            print("emit")
            emitter.setValue(0.0, forKey: "em")
            return emitter
        

        static func generateEmitterCells(image: UIImage) -> [CAEmitterCell] 
            var cells = [CAEmitterCell]()
            let cell = CAEmitterCell()
            cell.contents = image.cgImage
            cell.birthRate = 0.1
            cell.lifetime = 20
            cell.velocity = 250
            cell.emissionRange = (10 * (.pi/180))
            cell.scale = 0.9
            cell.scaleRange = 0.3
            cell.velocityRange = 100
            cells.append(cell)
            print("cells")
            return cells
        

    

    class ViewController : UIViewController
        override func viewDidLoad() 
            super.viewDidLoad()
            view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap)))

            let view2 = UIView(frame: self.view.frame)

            self.view.frame = CGRect(x: 0, y: 0, width: 320, height: 580)
            super.view.backgroundColor = UIColor.white
            self.view.addSubview(view2)
        

        @objc func handleTap() 
            rain()
        

        func rain() 
            let emitter = Emitter.get(with: UIImage(named: "Group 1493")!)
            emitter.emitterPosition = CGPoint(x: view.frame.width / 2, y: view.frame.height + 25)
            emitter.emitterSize = CGSize(width: view.frame.width, height: 2)
            self.view.layer.addSublayer(emitter)
        

    

    let controller = ViewController()
    PlaygroundPage.current.liveView = controller.view

【问题讨论】:

【参考方案1】:

您可以在第一次启动后将 lifetime 属性设置为 0

DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) emitter.lifetime = 0

【讨论】:

以上是关于只运行一次 CAEmitterLayer的主要内容,如果未能解决你的问题,请参考以下文章

CAEmitterLayer 动画在设备上不起作用

如何使一行代码在循环中运行一次,并且只运行下一行代码,直到前一行运行一次?

如何确保脚本运行一次且只运行一次

为啥 cProfile 只运行一次代码?

使某些代码只运行一次

只运行一次订阅