Piotr
Piotr

Reputation: 1617

flashing screen programatically with Swift (on 'screenshot taken')

In an effort to convert an Objective C example from here: How to flash screen programmatically? I wrote the following code:

func blinkScreen(){
    var wnd = UIApplication.sharedApplication().keyWindow;
    var v = UIView(frame: CGRectMake(0, 0, wnd!.frame.size.width, wnd!.frame.size.height))
    wnd!.addSubview(v);
    v.backgroundColor = UIColor.whiteColor()
    UIView.beginAnimations(nil, context: nil)
    UIView.setAnimationDuration(1.0)
    v.alpha = 0.0;
    UIView.commitAnimations();
}

But I am not sure where I should add UIView v removal code (on some event that is executed when animation ends ... but how?). Also - is my conversion correct?

Upvotes: 5

Views: 4946

Answers (2)

pmick
pmick

Reputation: 469

UIView provides class methods to both set an animations delegate, and provide selectors for when an animation will begin, and did finish.

Use the methods:

setAnimationDelegate(delegate:)
setAnimationWillStartSelector(selector:)
setAnimationDidStopSelector(selector:)

Alternatively, look into the UIView animation methods that allow you to provide closures that will be called on completion:

animateWithDuration(duration: delay: options: animations: completion:)

Within the function that you provide for didStopSelector, you could remove the UIView.

Upvotes: 0

Christian
Christian

Reputation: 22343

You were close to the solution. But you can make it even easier with completion-blocks in swift:

if let wnd = self.view{

    var v = UIView(frame: wnd.bounds)
    v.backgroundColor = UIColor.redColor()
    v.alpha = 1

    wnd.addSubview(v)
    UIView.animateWithDuration(1, animations: {
        v.alpha = 0.0
        }, completion: {(finished:Bool) in
            println("inside")
            v.removeFromSuperview()
    })
}

As you see, First I check if there is a view and then I just set the bounds of the view to the flash view. One important step is to set a background color. Otherwise you won't see any flash effect. I've set the backgroundColor to red, so that you can see it easier in the example. But you can of course use any color.

Then, the fun starts with the UIView.animateWithDuration part. As you see, I've replaced your startAnimation etc. code with a block. It reads like that: First you set the animation duration at 1 second. After that you start the animation by setting the alpha to 0. Then, after the animation is done, I remove the view from its superview.

That's all you need to reproduce the screenshot effect.

Upvotes: 12

Related Questions