2012-07-30 37 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