如何使用一个按钮打开/关闭手电筒? [英] How to turn flashlight on/off using one button?

查看:480
本文介绍了如何使用一个按钮打开/关闭手电筒?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以用一个按钮打开手电筒,然后用另一个按钮关闭。但我只想用一个按钮来做。但是,我没有允许我使用bool isSelected方法的框架。所以我对如何在一个按钮中将两个函数合并在一起非常无能为力。

I can turn my flashlight on with one button and turn it off with another. But I want to do it with only one button. However, I don't have a framework which allows me to use the bool isSelected method. So I'm quite clueless on how to merge both functions together in one button.

这是有效的代码:

-(void)onButtonPressed 
{

AVCaptureDevice *flashLight = [AVCaptureDevice 
defaultDeviceWithMediaType:AVMediaTypeVideo];
if([flashLight isTorchAvailable] && [flashLight
isTorchModeSupported:AVCaptureTorchModeOn])
{
    BOOL success = [flashLight lockForConfiguration:nil];
    if(success){
        [flashLight setTorchMode:AVCaptureTorchModeOn];
        [flashLight unlockForConfiguration];
    }
}

}

我用关闭手电筒。

-(void)offButtonPressed {

AVCaptureDevice *flashLight = [AVCaptureDevice
defaultDeviceWithMediaType:AVMediaTypeVideo];
if([flashLight isTorchAvailable] && [flashLight
isTorchModeSupported:AVCaptureTorchModeOn])
{
    BOOL success = [flashLight lockForConfiguration:nil];
    if(success){
        [flashLight setTorchMode:AVCaptureTorchModeOff];
        [flashLight unlockForConfiguration];
    }
}


}



<我不是特别关注它的完成方式。只要手电筒在第一次打开时打开并在第二次打开时关闭,我就不会在乎这种方法。

I'm not particular about the way it's done. As long as the flashlight turns on with the first tap and turns off on the second, I couldn't care less about the method.

但是,我正在使用以编程方式编写的barbuttonitems,所以请不要给我IBAction方法。如果建议的方法尽可能简单,我也很感激,我认为我现在使用手电筒的方式过于复杂。

However, I'm using barbuttonitems made programatically, so please don't give me IBAction methods. I'd also appreciate it if the method suggested is as simple as possible, I think the way I'm using the flashlight right now is overly complex.

推荐答案

我刚在我的应用上实现了这个功能。回答你的问题,这里是如何在一种方法中合并两个函数。

I've just implemented this feature on my app. Answering your question, here is how to merge both functions in one method.

- (void) flashlight
{
    AVCaptureDevice *flashLight = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([flashLight isTorchAvailable] && [flashLight isTorchModeSupported:AVCaptureTorchModeOn])
    {
        BOOL success = [flashLight lockForConfiguration:nil];
        if (success) 
        {
            if ([flashLight isTorchActive]) {
                [flashLight setTorchMode:AVCaptureTorchModeOff];
            } else {
                [flashLight setTorchMode:AVCaptureTorchModeOn];
            }
            [flashLight unlockForConfiguration];
        }
    }
}

这篇关于如何使用一个按钮打开/关闭手电筒?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆