如何使用if / else条件进行手电筒开关?

时间:2012-07-30 23:57:12

标签: ios uiswitch

所以我有一个UISwitch用于我的叠加,每次相机出现时都会出现。现在,当我打开按钮或将开关向右滑动(在模式下)时,手电筒会亮起。但当我将其切换到左侧时,它不会关闭。我做错了什么?

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

1 个答案:

答案 0 :(得分:1)

重新格式化代码后,您的else子句似乎位于错误的位置。尝试在第一个else块结束后移动if

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