用Swift编程实现屏幕闪烁(在“截图已拍摄”时)。

5
为了将这个Objective C的例子转换成Swift:How to flash screen programmatically?,我编写了以下代码:
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的移除代码(在动画结束时执行的某个事件上...但是如何实现?)。此外,我的转换正确吗?
2个回答

12
你已经接近解决方案了。但是你可以使用Swift中的完成块(completion-blocks)使其变得更加简单:
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等代码。它读起来像这样:首先,您将动画持续时间设置为1秒钟。之后,通过将alpha设置为0来启动动画。然后,在动画完成后,我将视图从其superview中移除。

这就是您需要重现截屏效果的全部内容。


手机的亮度级别怎么样?这个屏幕闪光会受到影响,有没有办法让屏幕在闪光时自动设置为全屏亮度并变成自动调节模式? - lorenzo gonzalez

0

UIView提供类方法来设置动画代理,并为动画开始和完成时提供选择器。

使用以下方法:

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

或者,可以查看UIView动画方法,这些方法允许您提供闭包,在完成时将被调用:

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接