Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 456
Piotr Avatar asked Dec 19 '22 06:12

Piotr


1 Answers

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.

like image 129
Christian Avatar answered Dec 24 '22 02:12

Christian