So I have made a custom UIButton and added it to the code and made the connections in interfacebuiler. I want the button to work as a on and off switch, how do I do this correctly? I’m a beginner at iphone development and this is for a school project for this class I’m taking during the summer to get a head start for next semester.
So if anyone can help me understand how to do this the right way and maybe write comments in the code. Thanks for all the help.
David H.
Here’s my code:
//
// FlashlightViewController.h
//
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface FlashlightViewController : UIViewController {
AVCaptureSession *torchSession;
IBOutlet UIButton *button;
}
-(IBAction)pressButton:(id) sender;
@property (nonatomic, retain) AVCaptureSession *torchSession;
@property (nonatomic, retain) IBOutlet UIButton *button;
@end
Here is the .m file
//
// FlashlightViewController.m
//
#import "FlashlightViewController.h"
@implementation FlashlightViewController
@synthesize torchSession;
@synthesize button;
- (void)viewDidLoad {
AVCaptureSession *session = [[AVCaptureSession alloc] init];
[session beginConfiguration];
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device hasTorch] && [device hasFlash]){
[device lockForConfiguration:nil];
[device setTorchMode:AVCaptureTorchModeOn];
[device setFlashMode:AVCaptureFlashModeOn];
[device unlockForConfiguration];
AVCaptureDeviceInput *flashInput = [AVCaptureDeviceInput deviceInputWithDevice:device error: nil];
if (flashInput){
[session addInput:flashInput];
}
AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
[session addOutput:output];
[output release];
[session commitConfiguration];
[session startRunning];
}
[self setTorchSession:session];
[session release];
[super viewDidLoad];
}
- (void)viewDidUnload {
self.button = nil;
}
- (void)dealloc {
[TorchSession release];
[button release];
[super dealloc];
}
-(IBAction)pressButton : (id) sender{
}
@end
In your
@interfacesection (.h), you also needIBOutlet IBAction pressButton;. Then, in Interface Builder, in the inspector (outlet section), select File’s Owner, and connectpressButton:to the UIButton’sTouch Up Insideaction.To toggle the torch state, add
BOOL torchAlreadyOn;to the@interfacesection (.h). Then, move yourviewDidLoadcustom code to thepressButtonmethod. Then, at the end of thepressButtonmethod, add:Then, everywhere where you set the torch state to on, enclose it in an if…else statement which checks the
BOOL: