使用Swift以编程方式闪烁屏幕(在“屏幕截图”上)

为了从这里转换Objective C示例: 如何以编程方式刷屏? 我写了下面的代码:

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(); } 

但我不知道应该在哪里添加UIView v移除代码(在animation结束时执行的某些事件,但是如何执行?)。 另外 – 我的转换是否正确?

你接近解决scheme。 但是你可以使用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() }) } 

正如你看到的,首先我检查是否有一个视图,然后我只是将视图的边界设置为闪存视图。 一个重要的步骤是设置背景颜色。 否则,你将看不到任何闪光效果。 我已经将backgroundColor设置为红色,以便您可以在示例中更轻松地看到它。 但是,你当然可以使用任何颜色。

然后,乐趣开始于UIView.animateWithDuration部分。 正如你所看到的,我用一个块代替了你的startAnimation等代码。 它是这样读的:首先你设置animation持续时间为1秒。 之后,通过将alpha设置为0来启动animation。然后,在完成animation之后,从其超级视图中删除视图。

这就是所有你需要重现的截图效果。

UIView提供了类方法来设置一个animation委托,并提供animation开始的select器,并完成。

使用方法:

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

或者,查看UIViewanimation方法,这些方法允许您提供将在完成时调用的闭包:

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

在为didStopSelector提供的函数中,可以删除UIView。