2012-07-30 55 views
0

所以我有一个UISwitch用于覆盖层,每次出现相机时都会出现。现在,当我打开开启按钮或向右滑动开关(开启模式)时,手电筒开启。但是当我将它切换到左侧时,它不会关闭。我究竟做错了什么?如何使用手电筒开关的if/else条件?

- (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

随着您的代码重新格式化,看起来您的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]; 
      } 
     } 
    } 
} 
+0

这工作有如神助。谢谢你,先生。它背后的逻辑是什么? – 2012-07-31 02:33:50

+0

在最外层的'if'语句没有'else'子句之前。正因为如此,函数中的所有代码只有在'self.mySwitch.on'为true时才会运行。现在,在'self.mySwitch.on'不正确的情况下,运行关闭手电筒的代码。 – mopsled 2012-07-31 04:19:40