How do I invalidate CADisplayLink with a UIButton?

112 Views Asked by At

Extreme noob. I define a CADisplayLink, then I want to invalidate it later using a UIButton. I get the error 'cannot find in scope' because (I assume) the link is initialized inside the func. Cannot figure out how to "get inside" the func to invaidate it. Code: ``` func myDisplayLink() {let displayLink = CADisplayLink(target: self, selector: #selector(myCycle)) displayLink.add(to: .current, forMode: RunLoop.Mode.default) }

@IBAction func OFF(_ sender: UIButton)
{ ????? }
```
1

There are 1 best solutions below

3
SuperTully On BEST ANSWER

You can declare it as an optional outside the scope of your function, at the root of your class then just initialize it in your function, like so:

class: SomeClass {

 var displayLink: CADisplayLink?

 func myDisplayLink() {
  displayLink = CADisplayLink(target: self, selector: #selector(myCycle))
  displayLink!.add(to: .current, forMode: RunLoop.Mode.default) 
 }

 @IBAction func OFF(_ sender: UIButton) {
  displayLink!.invalidate()
 }

}