iOS 闪光灯按钮封装

#import "SSFlashLightButton.h"
#import //调用闪光灯需要导入该框架
@implementation SSFlashLightButton

+ (instancetype)buttonWithType:(UIButtonType)buttonType{
    SSFlashLightButton *flashBtn = [super buttonWithType:buttonType];
    flashBtn.titleLabel.font = [UIFont systemFontOfSize:11];
    flashBtn.backgroundColor = [UIColor purpleColor];
    [flashBtn addTarget:self action:@selector(openFlash:) forControlEvents:UIControlEventTouchUpInside];
    return flashBtn;
}


+ (void)openFlash:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.isSelected == YES) { //打开闪光灯
        AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        NSError *error = nil;
        if ([captureDevice hasTorch]) {
            BOOL locked = [captureDevice lockForConfiguration:&error];
            if (locked) {
                captureDevice.torchMode = AVCaptureTorchModeOn;
                [captureDevice unlockForConfiguration];
            }
        }
    }else{//关闭闪光灯
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if ([device hasTorch]) {
            [device lockForConfiguration:nil];
            [device setTorchMode: AVCaptureTorchModeOff];
            [device unlockForConfiguration];
        }
    }
}
@end

你可能感兴趣的:(iOS 闪光灯按钮封装)