I'm using Interface Builder to design a static table view:
The orange bar is a custom subclassed view. Each other view is retained the same way, but for some reason only my custom view disappears. Trying to access it's properties later leads to a null for things I explicitly set, but no EXEC_BAD_ACCESS's.
Custom View code:
#import "EditableLabel.h"
#implementation EditableLabel
#synthesize font;
#synthesize maxSize;
#synthesize textColor;
- (void)awakeFromNib{
[self innerInit];
}
- (id)initWithFrame:(CGRect)frame
{
NSLog(#"got init");
self = [super initWithFrame:frame];
if (self) {
[self innerInit];
}
return self;
}
-(void)innerInit{
self.font = [UIFont systemFontOfSize:[UIFont systemFontSize]]; //default sys font, set this for pretty
self.maxSize = self.frame.size; //set this for pretty too
self.textColor = [UIColor blackColor];
self.isEditting = NO;
self.button = [UIButton buttonWithType:UIButtonTypeSystem];
self.button.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
self.button.userInteractionEnabled=YES;
self.button.hidden=NO;
self.button.titleLabel.font=font;
[self.button setTitleColor:textColor forState:UIControlStateNormal];
[self.button addTarget:self action:#selector(edit) forControlEvents:UIControlEventTouchUpInside];
[self.button setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
[self.button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
[self addSubview:self.button];
self.editField = [[UITextField alloc] initWithFrame:self.button.frame];
self.editField.font=font;
self.editField.textColor = textColor;
self.editField.userInteractionEnabled=YES;
self.editField.hidden=YES;
self.editField.borderStyle = UITextBorderStyleRoundedRect;
[self.editField addTarget:self action:#selector(finishEditting) forControlEvents:UIControlEventEditingDidEnd];
[self.editField setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
[self.editField setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
[self addSubview:self.editField];
[self bringSubviewToFront:self.button];
}
-(void)setTextFieldDelegate:(id)viewcontroller{
self.editField.delegate = viewcontroller;
}
-(void)edit{
[self flipWithCompletionBlock:^(BOOL done){
if (done){
self.isEditting=YES;
self.button.enabled=NO;
}
}];
}
-(void)finishEditting{
[self flipWithCompletionBlock:^(BOOL done){
if (done){
self.isEditting=NO;
self.button.enabled=YES;
[self.button setTitle:self.editField.text forState:UIControlStateNormal];
}
}];
}
-(NSString*)text{
return self.button.titleLabel.text;
}
-(void)setText:(NSString*)text{
self.editField.text=text;
[self.button setTitle:text forState:UIControlStateNormal];
}
-(UIColor*)backgroundColor{
return self.button.backgroundColor;
}
-(void)setBackgroundColor:(UIColor *)backgroundColor{
[self.button setBackgroundColor:backgroundColor];
[self.editField setBackgroundColor:backgroundColor];
}
-(void)setAlignmentVertical:(UIControlContentVerticalAlignment)vert horizontalAlignment:(UIControlContentHorizontalAlignment)horiz{
[self.button setContentHorizontalAlignment:horiz];
[self.button setContentVerticalAlignment:vert];
[self.editField setContentHorizontalAlignment:horiz];
[self.editField setContentVerticalAlignment:vert];
}
- (void)flipWithCompletionBlock:(void (^)(BOOL))block{
[UIView transitionWithView:self
duration:.3
options:UIViewAnimationOptionTransitionFlipFromTop
animations:^{
if (self.isEditting){
self.editField.hidden=YES;
self.button.hidden=NO;
[self bringSubviewToFront:self.button];
}
else {
self.button.hidden=YES;
self.editField.hidden=NO;
[self bringSubviewToFront:self.editField];
}
} completion:block];
}
#end
in my view controller.h I have #property (strong, nonatomic) IBOutlet EditableLabel *userNameEditField;, and every other view is retained fine. For some reason, only my subclass is released.
Related
So I have a UISwitch that backgroundColor already set to clearColor in tableViewCell.m :
- (instancetype)initWithStyle:(UITableViewCellStyle)style
reuseIdentifier:(NSString *)reuseIdentifier
{
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])
{
self.selectionStyle = UITableViewCellSelectionStyleNone;
self.backgroundColor = [UIColor colorWithHexString:#"#333333"];
[self initUI];
}
return self;
}
- (void)initUI {
[self addSubview:self.topLine];
[self addSubview:self.imgView];
[self addSubview:self.titleLab];
[self addSubview:self.rightView];
[self addSubview:self.rightSwitch];
[self addSubview:self.cellLine];
[self addSubview:self.bottomLine];
}
- (UISwitch *)rightSwitch {
if (!_rightSwitch) {
self.rightSwitch = [[UISwitch alloc] init];
self.rightSwitch.frame = CGRectMake(253*kScaleXAndWidth, 8*kScaleYAndHeight, 51*kScaleXAndWidth, 31*kScaleYAndHeight);
self.rightSwitch.hidden = YES;
[self.rightSwitch setBackgroundColor:[UIColor clearColor]];
[self.rightSwitch addTarget:self action:#selector(rightSwitchClick:) forControlEvents:UIControlEventTouchUpInside];
}
return _rightSwitch;
}
rightSwitchClick is a block, then in cellForRowAtIndexPath TableViewController.m :
QuickLoginCell *cell = [tableView dequeueReusableCellWithIdentifier:QuickLoginCellID forIndexPath:indexPath];
cell.rightView.hidden = YES;
cell.rightSwitch.hidden = NO;
__block QuickLoginCell *blockCell = cell;
if (isIDlogin) {
[cell.rightSwitch setEnabled:NO];
}
else{
[cell.rightSwitch setEnabled:YES];
}
cell.rightSwitch.on = NO;
cell.bottomLine.hidden = NO;
if (![BetwayUtils isEmptyString:patternLock]) {
cell.rightSwitch.on = YES;
cell.bottomLine.hidden = YES;
}
[cell.imgView setImage:[UIImage imageNamed:#"ic_patternLock"]];
cell.rightSwitchAddClick = ^{
if (blockCell.rightSwitch.on) {
PatternLockViewController *vc = [PatternLockViewController new];
[strongSelf.navigationController pushViewController:vc animated:YES];
}
else{
}
};
so when turn on it will directly go to PatternLockViewController, and after I have set the patternLock it will pop to TableViewController again and the switch will be turned on now. the problem is when I try to switch it off the backgroundColor suddenly change to white like this :
When I remove :
PatternLockViewController *vc = [PatternLockViewController new];
[strongSelf.navigationController pushViewController:vc animated:YES];
so inside the block there is no code and the UISwitch backgroundColor is clearColor, I tried to switch on and off and it works as it supposed to be. so i am a little bit confused on this matter since I dont set UISwitch backgroundColor to white anywhere.
UPDATE
Already tried using delegate to refresh table when pop from patternlockviewcontroller but still no avail
I solve it using :
- (void)prepareForReuse {
[super prepareForReuse];
[self.rightSwitch setBackgroundColor:[UIColor clearColor]];
[self.rightSwitch setTintColor:[UIColor whiteColor]];
[self.rightSwitch setThumbTintColor:[UIColor whiteColor]];
}
on my tableViewCell.m I hope it will help someone here.
I am working on a project in which I create a subclass for UIButton for setting the gradient background colour.Its working fine but now there are two tabs in a ViewController there is two buttons suppose A and B. I want to change colour of button A when I clicked on Button B same like tabs functionality:
Sub class of UIButton:
// .h_file
#import <UIKit/UIKit.h>
IB_DESIGNABLE
#interface grediantButton : UIButton
#property(nonatomic)IBInspectable UIColor*topColor;
#property(nonatomic)IBInspectable UIColor*bottomColor;
#property(nonatomic)IBInspectable CGFloat cornerRadius;
- (void)customInit;
#end
// .m file
#import "grediantButton.h"
#import "UIColor+myColor.h"
#implementation grediantButton
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.topColor = [UIColor clearColor];
self.bottomColor = [UIColor clearColor];
self.cornerRadius = 1;
[self customInit];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
[self customInit];
}
return self;
}
- (void)drawRect:(CGRect)rect {
[self customInit];
}
- (void)setNeedsLayout {
[super setNeedsLayout];
[self setNeedsDisplay];
}
- (void)prepareForInterfaceBuilder {
[self customInit];
}
- (void)customInit {
self.layer.cornerRadius = self.cornerRadius;
CAGradientLayer *gradientLayer = [[CAGradientLayer alloc] init];
gradientLayer.frame = self.bounds;
gradientLayer.cornerRadius = self.cornerRadius;
gradientLayer.colors = [NSArray arrayWithObjects:(id)[self.topColor CGColor], (id)[self.bottomColor CGColor],nil];
[self.layer setMasksToBounds:YES];
[self.layer insertSublayer:gradientLayer atIndex:0];
}
My VC Code:
#pragma mark:AddnewTownshipVC
- (IBAction)addnewTownShip:(id)sender {
[self.addnewTwnBtn setTopColor:[UIColor getTabTopColor]];
[self.addnewTwnBtn setBottomColor:[UIColor getTabBotColor]];
[self.viewalltownBtn setTopColor:[UIColor blackColor]];
[self.viewalltownBtn setBottomColor:[UIColor blackColor]];
}
#pragma mark:viewalltownshipVC
- (IBAction)viewAllTownship:(id)sender {
[self.addnewTwnBtn setTopColor:[UIColor blackColor]];
[self.addnewTwnBtn setBottomColor:[UIColor blackColor]];
[self.viewalltownBtn setTopColor:[UIColor getTabTopColor]];
[self.viewalltownBtn setBottomColor:[UIColor getTabBotColor]];
}
Tabs is like:
what happen when I click on black one tab
You should set state for UIButton multiple states.
For example, set different background images for different states.
[button setBackgroundImage:naomalImage forState:UIControlStateNormal];
[button setBackgroundImage:selectedImage forState:UIControlStateSelected];
And then, just control states.
- (IBAction)addnewTownShip:(id)sender {
button.selected = YES;
}
...
Thank you all for response.
I solved my issue by change some code in my - (void)customInit method
- (void)customInit {
self.layer.cornerRadius = self.cornerRadius;
CAGradientLayer *gradientLayer = [[CAGradientLayer alloc] init];
gradientLayer.frame = self.bounds;
gradientLayer.cornerRadius = self.cornerRadius;
gradientLayer.colors = [NSArray arrayWithObjects:(id)[self.topColor CGColor], (id)[self.bottomColor CGColor],nil];
[self.layer setMasksToBounds:YES];
if([[self.layer sublayers] objectAtIndex:0]){
[self.layer replaceSublayer:[[self.layer sublayers] objectAtIndex:0] with:gradientLayer];
}else{
[self.layer insertSublayer:gradientLayer atIndex:0];
}
}
and call this method in
#pragma mark:AddnewTownshipVC
- (IBAction)addnewTownShip:(grediantButton*)sender {
[sender setTopColor:[UIColor getTabTopColor]];
[sender setBottomColor:[UIColor getTabBotColor]];
[sender customInit];
[self.viewalltownBtn setTopColor:[UIColor blackColor]];
[self.viewalltownBtn setBottomColor:[UIColor blackColor]];
[self.viewalltownBtn customInit];
// sender.isSelected = true;
// self.viewalltownBtn.isSelected = false;
}
#pragma mark:viewalltownshipVC
- (IBAction)viewAllTownship:(grediantButton*)sender {
[self.addnewTwnBtn setTopColor:[UIColor blackColor]];
[self.addnewTwnBtn setBottomColor:[UIColor blackColor]];
[self.addnewTwnBtn customInit];
[sender setTopColor:[UIColor getTabTopColor]];
[sender setBottomColor:[UIColor getTabBotColor]];
[sender customInit];
}
simply go to the attribute inspector in storyboard see in bottom in it there has background colour you can change with it.
see here :-
https://i.stack.imgur.com/A6ecY.png
I have a UIButton inside a UIView, when the UIButton is selected I would like have a background colour of dark gray...is this possible?
UIView *toolbar = [[UIView alloc]initWithFrame:CGRectMake(10, 50, 40, 160)];
[toolbar setBackgroundColor:[UIColor colorWithWhite: 0.70 alpha:0.5]];
toolbar.layer.cornerRadius = 5;
UIButton *penTool = [UIButton buttonWithType:UIButtonTypeCustom];
penTool.frame = CGRectMake(5, 0, 30, 30);
[penTool setImage:[UIImage imageNamed:#"pen-but" inBundle:currentBundle compatibleWithTraitCollection:nil] forState:UIControlStateNormal];
[penTool addTarget:self action:#selector(drawButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
penTool.autoresizingMask = UIViewAutoresizingNone;
penTool.exclusiveTouch = YES;
penTool.tag = 1;
[toolbar addSubview:penTool];
What if you can do this?
[button setBackgroundColor:[UIColor greenColor]
forState:UIControlStateSelected];
Let's give a great API for every state, not just selected, just like UIButton default API's ability to change image and title for every state.
BGButton.h
#import <UIKit/UIKit.h>
#interface BGButton : UIButton
- (void)setBackgroundColor:(UIColor *)backgroundColor
forState:(UIControlState)state;
#end
BGButton.m
#import "BGButton.h"
#implementation BGButton {
NSMutableDictionary *_stateBackgroundColor;
}
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
_stateBackgroundColor = [[NSMutableDictionary alloc] init];
}
return self;
}
- (void)setBackgroundColor:(UIColor *)backgroundColor {
[super setBackgroundColor:backgroundColor];
/*
* If user set button.backgroundColor we will set it to
* normal state's backgroundColor.
* Check if state is on normal state to prevent background being
* changed for incorrect state when updateBackgroundColor method is called.
*/
if (self.state == UIControlStateNormal) {
[self setBackgroundColor:backgroundColor forState:UIControlStateNormal];
}
}
- (void)setBackgroundColor:(UIColor *)backgroundColor
forState:(UIControlState)state {
NSNumber *key = [NSNumber numberWithInt:state];
[_stateBackgroundColor setObject:backgroundColor forKey:key];
}
/*
* state is synthesized from other flags. So we can't use KVO
* to listen for state changes.
*/
- (void)setSelected:(BOOL)selected {
[super setSelected:selected];
[self stateDidChange];
}
- (void)setEnabled:(BOOL)enabled {
[super setEnabled:enabled];
[self stateDidChange];
}
- (void)setHighlighted:(BOOL)highlighted {
[super setHighlighted:highlighted];
[self stateDidChange];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[super touchesBegan:touches withEvent:event];
[self stateDidChange];
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[super touchesMoved:touches withEvent:event];
[self stateDidChange];
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[super touchesEnded:touches withEvent:event];
[self stateDidChange];
}
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[super touchesCancelled:touches withEvent:event];
[self stateDidChange];
}
- (void)stateDidChange {
[self updateBackgroundColor];
}
- (void)updateBackgroundColor {
NSNumber *key = [NSNumber numberWithInt:self.state];
self.backgroundColor = [_stateBackgroundColor objectForKey:key];
}
#end
You can use it like the default UIButton API
BGButton *button = [[BGButton alloc] init];
[button setBackgroundColor:[UIColor greenColor]
forState:UIControlStateSelected];
[button setBackgroundColor:[UIColor blueColor]
forState:UIControlStateHighlighted];
[button setBackgroundColor:[UIColor orangeColor]
forState:UIControlStateDisabled];
Even if you use
button.backgroundColor = [UIColor redColor];
You will stay safe, it will be translated into
[button setBackgroundColor:[UIColor redColor]
forState:UIControlStateNormal];
if you have this code
[self.view addSubview:toolbar];
then just implement your button selector
-(void)drawButtonTapped:(UIButton*)button{
if (button.selected) {
button.backgroundColor = [UIColor clearColor];
button.selected = NO;
}else{
button.backgroundColor = [UIColor darkGrayColor];
button.selected = YES;
}
}
I don't know why guys would go through such trouble when we have this functionality built-in inside UIButton. All you need to do is use UIButtonTypeSystem That's all.
[UIButton buttonWithType:UIButtonTypeSystem]
Seriously, there's nothing more to it. Have a look at it's behavior in the screenshots.
INTERFACE BUILDER
RUN TIME
Want to change color, set tintColor to color of your choice.
ADVANTAGES
Covers titles with dynamic lengths. Not applied on all button width.
When selected, title color is transparent, your background can be seen through, try to use an image as a background.
Let's hope you have at least iOS7 as deployment target. UIButtonTypeSystem was introduce with revised UI design guidelines of iOS7 and has been there for almost 3 years.
Good Luck!
I used a UIButton subclass here:
#import "CustomButton.h"
#interface CustomButton()
#property (nonatomic,strong) UIColor *originalColor;
#end
#implementation CustomButton
- (void)didMoveToSuperview
{
self.originalColor = self.superview.backgroundColor;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
self.superview.backgroundColor = [UIColor grayColor];
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:self];
if ([self hitTest:location withEvent:nil]) {
self.superview.backgroundColor = [UIColor grayColor];
self.originalColor = self.superview.backgroundColor;
}
else
{
self.superview.backgroundColor = self.originalColor;
}
}
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
self.superview.backgroundColor = self.originalColor;
}
#end
If you subclass your button from this class, It should give you the desired effect. This also gives you the highlight effect. If you wish you can disable it by removing the line on touchesBegan.
Just try to Override the UIButton with the following Method...
- (void)setHighlighted:(BOOL)highlighted {
[super setHighlighted:highlighted];
if (highlighted) {
self.backgroundColor = [UIColor darkGray];
}
}
I think you'll be want to change the selectedImage for flexibility not the background.
Add another image (e.g. pen-but-selected) in the project. Add this 2nd line for setImage:
[penTool setImage:[UIImage imageNamed:#"pen-but-selected" inBundle:currentBundle compatibleWithTraitCollection:nil] forState:UIControlStateSelected];
- (void)drawButtonTapped:(UIButton *)button {
button.selected = !button.selected;
}
If you still want to change background color. #jamil's answer would work. Make sure the buttonImage has transparent part so you can see the buttonBackground through the buttonImage.
Try using a boolean, or some other reference to the selection state of the button. You could also make use of a 'highlightColour' as well as the 'selectedColour' if you wanted closer control (should probably do this for better UX).
bool buttonIsSelected = false;
UIColor * selectedColour = [UIColor redColor];
UIColor * defaultColour = [UIColor blueColor];
UIButton * button = [UIButton new];
button.frame = CGRectMake(0,0,100,100);
button.backgroundColor = [UIColor redColor];
[self.view addSubview:button];
[button addTarget:self action:#selector(buttonTouchUp:) forControlEvents:UIControlEventTouchUpInside];
[button addTarget:self action:#selector(buttonTouchCancel:) forControlEvents:UIControlEventTouchCancel];
[button addTarget:self action:#selector(buttonTouchDown:) forControlEvents:UIControlEventTouchDown];
-(void)buttonTouchUp:(UIButton *)button {
if (buttonIsSelected){
buttonIsSelected = false;
button.backgroundColor = defaultColour;
} else {
buttonIsSelected = true;
button.backgroundColor = selectedColour;
}
}
-(void)buttonTouchCancel:(UIButton *)button {
button.backgroundColor = defaultColour;
if (buttonIsSelected){
button.backgroundColor = selectedColour;
}
}
-(void)buttonTouchDown:(UIButton *)button {
button.backgroundColor = selectedColour;
}
-(void)OnSelect:(UIButton*)button{
if (button.selected) {
button.backgroundColor = [UIColor blue];
button.selected = NO;
}else{
button.backgroundColor = [UIColor darkGrayColor];
button.selected = YES;
}
}
use the above this will work..
-(void)buttonTapped:(UIButton*)button{
button.selected =! button.selected;
if (button.selected)
button.backgroundColor = [UIColor grayColor];
else
button.backgroundColor = [UIColor clearColor];
}
I'm doing an application that on a specific part of the application, the user will be able to take a picture from the camera or select from the Album and this image will be shown on the ViewController.
This is kind of easy, but, what I need, that I'm not being able to do is:
-I don't want that the Camera open full screen, I want it to 'open' on the ViewController that the user is, in the exactly same place as where the image will be, inside a circle.
I was able to make the Camera not open full screen, but I'm not being able to put this view inside the circle view and crop the photo according to the circle.
Here is my code, it might work if you create a standard project and I think that will help to understand what's going on:
VARIABLES
#property (nonatomic, strong) UIImagePickerController * picker;
#property (nonatomic, strong) UIImageView * photoView;
#property (nonatomic, strong) UIView * overlayView;
#property (nonatomic, strong) UIButton * takePhotoButton; //- function
#property (nonatomic, strong) UIButton * selectPhotoButton;
#property (nonatomic, strong) UIButton * takePicture; //- action
CODE
#interface CameraViewController ()
{
BOOL isFromAlbum;
}
#end
#implementation CameraViewController
#synthesize photoView;
#synthesize picker;
#synthesize takePicture;
#synthesize selectPhotoButton;
#synthesize takePhotoButton;
#synthesize overlayView;
#synthesize switchCameraButton;
#pragma mark -
#pragma mark Initialization & Life Cycle
- (void)viewDidLoad
{
[super viewDidLoad];
[self initInterface];
}
-(void)initInterface
{
[super addBackButton];
self.view.backgroundColor = [UIColor colorWithRed:026.0f/255.0f green:030.0f/255.0f blue:055.0f/255.0f alpha:1.0f];
self.takePhotoButton = [UIButton buttonWithType:UIButtonTypeSystem];
self.takePhotoButton.frame = CGRectMake(27.5f, self.view.frame.size.width/2 - 55, 110, 110);
self.takePhotoButton.layer.cornerRadius = self.takePhotoButton.frame.size.width / 2.0f;
[self.takePhotoButton setImage:[UIImage imageNamed:#"take-photo-btn"] forState:UIControlStateNormal];
[self.takePhotoButton addTarget:self action:#selector(takePhotoFunction) forControlEvents:UIControlEventTouchUpInside];
//[self.takePhotoButton setBackgroundColor:[UIColor colorWithRed:000.0f/255.0f green:255.0f/255.0f blue:000.0f/255.0f alpha:0.25f]];
[self.view addSubview:self.takePhotoButton];
self.selectPhotoButton = [UIButton buttonWithType:UIButtonTypeSystem];
self.selectPhotoButton.frame = CGRectMake(self.view.frame.size.width/2 + 27.5f, self.view.frame.size.width/2 - 55, 110, 110);
self.selectPhotoButton.layer.cornerRadius = self.selectPhotoButton.frame.size.width / 2.0f;
[self.selectPhotoButton setImage:[UIImage imageNamed:#"pick-photo-btn"] forState:UIControlStateNormal];
[self.selectPhotoButton addTarget:self action:#selector(selectPhoto) forControlEvents:UIControlEventTouchUpInside];
//[self.selectPhotoButton setBackgroundColor:[UIColor colorWithRed:0 green:255/255.0f blue:0 alpha:0.25f]];
[self.view addSubview:self.selectPhotoButton];
self.photoView = [[UIImageView alloc] init];
self.photoView.backgroundColor = [UIColor colorWithRed:255.0f/255.0f green:000.0f/255.0f blue:000.0f/255.0f alpha:0.25f];
self.photoView.frame = CGRectMake(0, 0, 320, 320);
self.photoView.layer.cornerRadius = self.photoView.frame.size.width / 2;
self.photoView.layer.masksToBounds = YES;
self.photoView.userInteractionEnabled = YES;
}
#pragma mark -
#pragma mark Button's Actions
- (void)takePhotoFunction
{
self.picker = [[UIImagePickerController alloc] init];
self.picker.delegate = self;
self.picker.allowsEditing = YES;
self.picker.sourceType = UIImagePickerControllerSourceTypeCamera;
self.picker.showsCameraControls = NO;
self.picker.view.frame = self.photoView.bounds;
[self.photoView addSubview:self.picker.view];
self.takePicture = [UIButton buttonWithType:UIButtonTypeSystem];
self.takePicture.frame = CGRectMake(self.photoView.frame.size.width/2 - 35, self.photoView.frame.size.height - 70, 70, 70);
[self.takePicture addTarget:self action:#selector(takePhotoAction:) forControlEvents:UIControlEventTouchUpInside];
[self.takePicture setBackgroundImage:[UIImage imageNamed:#"take-photo-action"] forState:UIControlStateNormal];
[self.photoView addSubview:self.takePicture];
self.switchCameraButton = [[UIButton alloc] init];
self.switchCameraButton.frame = CGRectMake(self.photoView.frame.size.width/2 - 35, self.photoView.frame.origin.y, 70, 70);
[self.switchCameraButton addTarget:self action:#selector(switchCamera:) forControlEvents:UIControlEventTouchUpInside];
[self.switchCameraButton setBackgroundImage:[UIImage imageNamed:#"reverse-camera-btn"] forState:UIControlStateNormal];
[self.photoView addSubview:self.switchCameraButton];
[self.view addSubview:self.photoView];
isFromAlbum = NO;
}
- (void)selectPhoto
{
self.picker = [[UIImagePickerController alloc] init];
self.picker.delegate = self;
self.picker.allowsEditing = YES;
self.picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
isFromAlbum = YES;
[self presentViewController:self.picker animated:YES completion:NULL];
}
-(IBAction)takePhotoAction:(id)sender
{
[self.picker takePicture];
}
-(IBAction)switchCamera:(id)sender
{
if (picker.cameraDevice == UIImagePickerControllerCameraDeviceFront)
{
picker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
}
else if (picker.cameraDevice == UIImagePickerControllerCameraDeviceRear)
{
picker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
}
}
#pragma mark -
#pragma mark PickerController Delegate Methods
- (void)imagePickerController:(UIImagePickerController *)myPicker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
//NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
UIImage *originalImage, *editedImage, *imageToSave;
// Handle a still image capture
//if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0) == kCFCompareEqualTo)
if (isFromAlbum == NO)
{
editedImage = (UIImage *) [info objectForKey:
UIImagePickerControllerEditedImage];
originalImage = (UIImage *) [info objectForKey:
UIImagePickerControllerOriginalImage];
if (editedImage)
{
imageToSave = editedImage;
}
else
{
imageToSave = originalImage;
}
// Save the new image (original or edited) to the Camera Roll
//UIImageWriteToSavedPhotosAlbum (imageToSave, nil, nil , nil);
[self.takePhotoButton removeFromSuperview];
[self.switchCameraButton removeFromSuperview];
[self.selectPhotoButton removeFromSuperview];
[self.picker.view removeFromSuperview];
[self.takePicture removeFromSuperview];
CGFloat minimumSide = fminf(imageToSave.size.width, imageToSave.size.height);
CGFloat finalSquareSize = 640.;
//create new drawing context for right size
CGRect rect = CGRectMake(0, 0, finalSquareSize, finalSquareSize);
CGFloat scalingRatio = 640.0/minimumSide;
UIGraphicsBeginImageContext(rect.size);
//draw
[imageToSave drawInRect:CGRectMake((minimumSide - originalImage.size.width)*scalingRatio/2., (minimumSide - originalImage.size.height)*scalingRatio/2., originalImage.size.width*scalingRatio, originalImage.size.height*scalingRatio)];
UIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//[self.photoView setImage:imageToSave];
[self.photoView setImage:croppedImage];
}
else
{
[self.takePhotoButton removeFromSuperview];
[self.selectPhotoButton removeFromSuperview];
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
[self.photoView setImage:chosenImage];
[self.view addSubview:self.photoView];
[myPicker dismissViewControllerAnimated:YES completion:NULL];
}
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)myPicker
{
//[picker.view removeFromSuperview];
[myPicker dismissViewControllerAnimated:YES completion:NULL];
}
#pragma mark -
#pragma mark NavigationController Methods
-(void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
[[UIApplication sharedApplication] setStatusBarHidden:NO];
}
With the code below, I get the following results:
A single view with a dark blue background.
2 green circles (the buttons)
Tapping on the left circle puts the camera's "sight" inside of it.
Tapping on the "take" button (at the bottom of the circle on the left) fires off the "takePhotoAction" method.
[Code]
// ViewController.m
#import "ViewController.h"
#interface ViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate> {
BOOL isFromAlbum;
}
#property (nonatomic, strong) UIImagePickerController * picker;
#property (nonatomic, strong) UIImageView * photoView;
#property (nonatomic, strong) UIView * overlayView;
#property (nonatomic, strong) UIButton * takePhotoButton; //- function
#property (nonatomic, strong) UIButton * selectPhotoButton;
#property (nonatomic, strong) UIButton * takePicture; //- action
#end
#implementation ViewController
#pragma mark -
#pragma mark Initialization & Life Cycle
- (void)viewDidLoad {
[super viewDidLoad];
[self initInterface];
}
-(void)initInterface {
self.view.backgroundColor = [UIColor colorWithRed:026.0f/255.0f green:030.0f/255.0f blue:055.0f/255.0f alpha:1.0f];
self.takePhotoButton = [UIButton buttonWithType:UIButtonTypeSystem];
self.takePhotoButton.frame = CGRectMake(27.5f, self.view.frame.size.width/2 - 55, 110, 110);
self.takePhotoButton.layer.cornerRadius = self.takePhotoButton.frame.size.width / 2.0f;
[self.takePhotoButton setImage:[UIImage imageNamed:#"take-photo-btn"] forState:UIControlStateNormal];
[self.takePhotoButton addTarget:self action:#selector(takePhotoFunction) forControlEvents:UIControlEventTouchUpInside];
[self.takePhotoButton setBackgroundColor:[UIColor colorWithRed:000.0f/255.0f green:255.0f/255.0f blue:000.0f/255.0f alpha:0.25f]];
[self.view addSubview:self.takePhotoButton];
self.selectPhotoButton = [UIButton buttonWithType:UIButtonTypeSystem];
self.selectPhotoButton.frame = CGRectMake(self.view.frame.size.width/2 + 27.5f, self.view.frame.size.width/2 - 55, 110, 110);
self.selectPhotoButton.layer.cornerRadius = self.selectPhotoButton.frame.size.width / 2.0f;
[self.selectPhotoButton setImage:[UIImage imageNamed:#"pick-photo-btn"] forState:UIControlStateNormal];
[self.selectPhotoButton addTarget:self action:#selector(selectPhoto) forControlEvents:UIControlEventTouchUpInside];
[self.selectPhotoButton setBackgroundColor:[UIColor colorWithRed:0 green:255/255.0f blue:0 alpha:0.25f]];
[self.view addSubview:self.selectPhotoButton];
self.photoView = [[UIImageView alloc] init];
self.photoView.backgroundColor = [UIColor colorWithRed:255.0f/255.0f green:000.0f/255.0f blue:000.0f/255.0f alpha:0.25f];
self.photoView.frame = self.takePhotoButton.frame;
self.photoView.layer.cornerRadius = self.photoView.frame.size.width / 2;
self.photoView.layer.masksToBounds = YES;
[self.photoView setUserInteractionEnabled:YES];
}
#pragma mark -
#pragma mark Actions
- (void)takePhotoFunction {
self.picker = [[UIImagePickerController alloc] init];
self.picker.delegate = self;
self.picker.allowsEditing = YES;
self.picker.sourceType = UIImagePickerControllerSourceTypeCamera;
self.picker.showsCameraControls = NO;
self.picker.view.frame = self.photoView.bounds;
[self.photoView addSubview:self.picker.view];
self.takePicture = [UIButton buttonWithType:UIButtonTypeSystem];
self.takePicture.frame = CGRectMake(self.photoView.frame.size.width/2 - 35, self.photoView.frame.size.height - 40, 70, 70);
[self.takePicture addTarget:self action:#selector(takePhotoAction:) forControlEvents:UIControlEventTouchUpInside];
[self.takePicture setBackgroundImage:[UIImage imageNamed:#"take-photo-action"] forState:UIControlStateNormal];
[self.photoView addSubview:self.takePicture];
[self.view addSubview:self.photoView];
isFromAlbum = NO;
}
- (void)selectPhoto {
self.picker = [[UIImagePickerController alloc] init];
self.picker.delegate = self;
self.picker.allowsEditing = YES;
self.picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
isFromAlbum = YES;
[self presentViewController:self.picker animated:YES completion:NULL];
}
-(IBAction)takePhotoAction:(id)sender {
[self.picker takePicture];
}
#pragma mark -
#pragma mark PickerController Delegate Methods
- (void)imagePickerController:(UIImagePickerController *)myPicker didFinishPickingMediaWithInfo:(NSDictionary *)info {
//NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
UIImage *originalImage, *editedImage, *imageToSave;
// Handle a still image capture
//if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0) == kCFCompareEqualTo)
if (isFromAlbum == NO) {
editedImage = (UIImage *) [info objectForKey:
UIImagePickerControllerEditedImage];
originalImage = (UIImage *) [info objectForKey:
UIImagePickerControllerOriginalImage];
if (editedImage) {
imageToSave = editedImage;
} else {
imageToSave = originalImage;
}
// Save the new image (original or edited) to the Camera Roll
//UIImageWriteToSavedPhotosAlbum (imageToSave, nil, nil , nil);
[self.takePhotoButton removeFromSuperview];
[self.selectPhotoButton removeFromSuperview];
[self.picker.view removeFromSuperview];
[self.takePicture removeFromSuperview];
[self.photoView setImage:imageToSave];
} else {
[self.takePhotoButton removeFromSuperview];
[self.selectPhotoButton removeFromSuperview];
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
[self.photoView setImage:chosenImage];
[self.view addSubview:self.photoView];
[myPicker dismissViewControllerAnimated:YES completion:NULL];
}
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)myPicker {
//[picker.view removeFromSuperview];
[myPicker dismissViewControllerAnimated:YES completion:NULL];
}
#pragma mark -
#pragma mark NavigationController Methods
-(void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
[[UIApplication sharedApplication] setStatusBarHidden:NO];
}
#end
Solved the issue of the "smaller image" on the PhotoView after taking a picture by cropping it as a square and just after, set the image of the PhotoView.
Solved the issue of the image "going up" a little bit after setting the image on PhotoView by 'setting' the picker.view frame on x: 0, y:-50, PhotoView.width, PhotoView.height.
Here is the fullcode:
#interface CameraViewController ()
{
BOOL isFromAlbum;
}
#end
#implementation CameraViewController
#synthesize photoView;
#synthesize picker;
#synthesize takePicture;
#synthesize selectPhotoButton;
#synthesize takePhotoButton;
#synthesize switchCameraButton;
#pragma mark -
#pragma mark Initialization & Life Cycle
- (void)viewDidLoad
{
[super viewDidLoad];
[self initInterface];
}
-(void)initInterface
{
[super addBackButton];
self.view.backgroundColor = [UIColor colorWithRed:026.0f/255.0f green:030.0f/255.0f blue:055.0f/255.0f alpha:1.0f];
self.takePhotoButton = [UIButton buttonWithType:UIButtonTypeSystem];
self.takePhotoButton.frame = CGRectMake(27.5f, self.view.frame.size.width/2 - 55, 110, 110);
self.takePhotoButton.layer.cornerRadius = self.takePhotoButton.frame.size.width / 2.0f;
[self.takePhotoButton setImage:[UIImage imageNamed:#"take-photo-btn"] forState:UIControlStateNormal];
[self.takePhotoButton addTarget:self action:#selector(takePhotoFunction) forControlEvents:UIControlEventTouchUpInside];
//[self.takePhotoButton setBackgroundColor:[UIColor colorWithRed:000.0f/255.0f green:255.0f/255.0f blue:000.0f/255.0f alpha:0.25f]];
[self.view addSubview:self.takePhotoButton];
self.selectPhotoButton = [UIButton buttonWithType:UIButtonTypeSystem];
self.selectPhotoButton.frame = CGRectMake(self.view.frame.size.width/2 + 27.5f, self.view.frame.size.width/2 - 55, 110, 110);
self.selectPhotoButton.layer.cornerRadius = self.selectPhotoButton.frame.size.width / 2.0f;
[self.selectPhotoButton setImage:[UIImage imageNamed:#"pick-photo-btn"] forState:UIControlStateNormal];
[self.selectPhotoButton addTarget:self action:#selector(selectPhoto) forControlEvents:UIControlEventTouchUpInside];
//[self.selectPhotoButton setBackgroundColor:[UIColor colorWithRed:0 green:255/255.0f blue:0 alpha:0.25f]];
[self.view addSubview:self.selectPhotoButton];
self.photoView = [[UIImageView alloc] init];
self.photoView.backgroundColor = [UIColor colorWithRed:255.0f/255.0f green:000.0f/255.0f blue:000.0f/255.0f alpha:0.25f];
self.photoView.frame = CGRectMake(0, 0, 320, 320);
self.photoView.layer.cornerRadius = self.photoView.frame.size.width / 2;
self.photoView.layer.masksToBounds = YES;
self.photoView.userInteractionEnabled = YES;
}
#pragma mark -
#pragma mark Button's Actions
- (void)takePhotoFunction
{
self.picker = [[UIImagePickerController alloc] init];
self.picker.delegate = self;
self.picker.allowsEditing = YES;
self.picker.sourceType = UIImagePickerControllerSourceTypeCamera;
self.picker.showsCameraControls = NO;
//self.picker.view.frame = self.photoView.bounds;
self.picker.view.frame = CGRectMake(0, -50, photoView.frame.size.width, photoView.frame.size.height + 50);
[self.photoView addSubview:self.picker.view];
self.takePicture = [UIButton buttonWithType:UIButtonTypeSystem];
self.takePicture.frame = CGRectMake(self.photoView.frame.size.width/2 - 35, self.photoView.frame.size.height - 70, 70, 70);
[self.takePicture addTarget:self action:#selector(takePhotoAction:) forControlEvents:UIControlEventTouchUpInside];
[self.takePicture setBackgroundImage:[UIImage imageNamed:#"take-photo-action"] forState:UIControlStateNormal];
[self.photoView addSubview:self.takePicture];
self.switchCameraButton = [[UIButton alloc] init];
self.switchCameraButton.frame = CGRectMake(self.photoView.frame.size.width/2 - 35, self.photoView.frame.origin.y, 70, 70);
[self.switchCameraButton addTarget:self action:#selector(switchCamera:) forControlEvents:UIControlEventTouchUpInside];
[self.switchCameraButton setBackgroundImage:[UIImage imageNamed:#"reverse-camera-btn"] forState:UIControlStateNormal];
[self.photoView addSubview:self.switchCameraButton];
[self.view addSubview:self.photoView];
isFromAlbum = NO;
}
- (void)selectPhoto
{
self.picker = [[UIImagePickerController alloc] init];
self.picker.delegate = self;
self.picker.allowsEditing = YES;
self.picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
isFromAlbum = YES;
[self presentViewController:self.picker animated:YES completion:NULL];
}
-(IBAction)takePhotoAction:(id)sender
{
[self.picker takePicture];
}
-(IBAction)switchCamera:(id)sender
{
if (picker.cameraDevice == UIImagePickerControllerCameraDeviceFront)
{
picker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
}
else if (picker.cameraDevice == UIImagePickerControllerCameraDeviceRear)
{
picker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
}
}
- (UIImage*)rotateUIImage:(UIImage*)sourceImage
{
CGSize size = sourceImage.size;
UIGraphicsBeginImageContext(CGSizeMake(size.height, size.width));
[[UIImage imageWithCGImage:[sourceImage CGImage] scale:1.0 orientation:UIImageOrientationDownMirrored] drawInRect:CGRectMake(0,0,size.height ,size.width)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
#pragma mark -
#pragma mark PickerController Delegate Methods
- (void)imagePickerController:(UIImagePickerController *)myPicker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
//NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
UIImage *originalImage, *editedImage, *imageToSave;
// Handle a still image capture
//if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0) == kCFCompareEqualTo)
if (isFromAlbum == NO)
{
editedImage = (UIImage *) [info objectForKey:
UIImagePickerControllerEditedImage];
originalImage = (UIImage *) [info objectForKey:
UIImagePickerControllerOriginalImage];
if (editedImage)
{
imageToSave = editedImage;
}
else
{
imageToSave = originalImage;
}
// Save the new image (original or edited) to the Camera Roll
//UIImageWriteToSavedPhotosAlbum (imageToSave, nil, nil , nil);
[self.takePhotoButton removeFromSuperview];
[self.switchCameraButton removeFromSuperview];
[self.selectPhotoButton removeFromSuperview];
[self.picker.view removeFromSuperview];
[self.takePicture removeFromSuperview];
CGFloat minimumSide = fminf(imageToSave.size.width, imageToSave.size.height);
CGFloat finalSquareSize = 640.;
//create new drawing context for right size
CGRect rect = CGRectMake(0, 0, finalSquareSize, finalSquareSize);
CGFloat scalingRatio = 640.0/minimumSide;
UIGraphicsBeginImageContext(rect.size);
//draw
[imageToSave drawInRect:CGRectMake((minimumSide - originalImage.size.width)*scalingRatio/2., (minimumSide - originalImage.size.height)*scalingRatio/2., originalImage.size.width*scalingRatio, originalImage.size.height*scalingRatio)];
UIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// if (picker.cameraDevice == UIImagePickerControllerCameraDeviceFront)
// {
// [self rotateUIImage:croppedImage];
// }
//[self.photoView setImage:imageToSave];
[self.photoView setImage:croppedImage];
}
else
{
[self.takePhotoButton removeFromSuperview];
[self.selectPhotoButton removeFromSuperview];
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
[self.photoView setImage:chosenImage];
[self.view addSubview:self.photoView];
[myPicker dismissViewControllerAnimated:YES completion:NULL];
}
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)myPicker
{
//[picker.view removeFromSuperview];
[myPicker dismissViewControllerAnimated:YES completion:NULL];
}
#pragma mark -
#pragma mark NavigationController Methods
-(void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
[[UIApplication sharedApplication] setStatusBarHidden:NO];
}
#end
I have a parent view that allows you to see post in a UITableView. In its Navigation Bar I have a post button that when pressed presents a UIView subclass and shows it on the top of the screen. I have an image on that UIView that when tapped I want to present the UIImagePickerController to allow users to pick an image to post to the service. How can I do this since my subview is not a view controller it cannot present the UIImagePickerController.
Below is my subview code.
#import "PostView.h"
#implementation PostView
#synthesize attachedLabel;
#synthesize postButton;
#synthesize textView;
#synthesize characterLimit;
#synthesize attachImage;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
originalFrame = frame;
NSArray *xib = [[NSBundle mainBundle] loadNibNamed:#"PostView" owner:self options:nil];
PostView *view = [xib objectAtIndex:0];
[view setBackgroundColor:[UIColor whiteColor]];
[view setAlpha:0.7f];
attachedLabel = [[UILabel alloc] initWithFrame:CGRectMake(204, 212, 56, 21)];
attachedLabel.textColor = [UIColor blackColor];
[attachedLabel setText:#"Attached"];
attachedLabel.backgroundColor = [UIColor clearColor];
attachedLabel.font = [UIFont fontWithName:text_font_name size:12.0];
characterLimit = [[UILabel alloc] initWithFrame:CGRectMake(246, 13, 50, 21)];
[characterLimit setTextAlignment:NSTextAlignmentRight];
characterLimit.textColor = [UIColor blackColor];
characterLimit.backgroundColor = [UIColor clearColor];
characterLimit.font = [UIFont fontWithName:text_font_name size:12.0];
attachImage = [[UIImageView alloc] initWithFrame:CGRectMake(270, 208, 30, 30)];
[attachImage setImage:[UIImage imageNamed:#"attachphoto30x30.png"]];
[self.textView setDelegate:self];
[self.textView setAlpha:0.7f];
[self.textView setTextColor:[UIColor whiteColor]];
[self.textView setBackgroundColor:[UIColor clearColor]];
self.layer.cornerRadius = 10.0f;
self.layer.masksToBounds = YES;
[self addSubview:view];
[self addSubview:characterLimit];
[self addSubview:attachedLabel];
[self addSubview:attachImage];
}
return self;
}
- (IBAction)openCamera:(id)sender
{
UIImagePickerController *controller = [[UIImagePickerController alloc] init];
controller.delegate = self;
//[self presentViewController:controller animated:YES completion:nil];
NSLog(#"%#", #"Image Tapped");
}
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
/*[picker dismissViewControllerAnimated:YES completion:nil];
UIImage *image = [info objectForKey: UIImagePickerControllerOriginalImage];
UIImage *scale = [image scaleToSize:CGSizeMake(320.0f, 548.0f)];
imageData = UIImageJPEGRepresentation(scale, 1);
encodedImage = [self Base64Encode:imageData];
[attachedLabel setHidden:NO];
*/
}
#pragma mark Custom alert methods
- (IBAction)postAction:(id)sender
{
[self hide];
}
- (void)show
{
//prepare attachImage
attachImage.userInteractionEnabled = YES;
UITapGestureRecognizer *tapAttach = [[UITapGestureRecognizer alloc]
initWithTarget:self action:#selector(openCamera:)];
tapAttach.numberOfTapsRequired = 1;
[self.attachImage addGestureRecognizer:tapAttach];
isShown = YES;
self.transform = CGAffineTransformMakeScale(0.1, 0.1);
self.alpha = 0;
[UIView beginAnimations:#"showAlert" context:nil];
[self setBackgroundColor:[UIColor clearColor]];
[UIView setAnimationDelegate:self];
self.transform = CGAffineTransformMakeScale(1.1, 1.1);
self.alpha = 1;
[UIView commitAnimations];
}
- (void)hide
{
isShown = NO;
[UIView beginAnimations:#"hideAlert" context:nil];
[UIView setAnimationDelegate:self];
[[NSNotificationCenter defaultCenter] postNotificationName:#"hidePostView_Notification" object:nil];
self.transform = CGAffineTransformMakeScale(0.1, 0.1);
self.alpha = 0;
[UIView commitAnimations];
}
- (void)toggle
{
if (isShown)
{
[self hide];
} else
{
[self show];
}
}
#pragma mark Animation delegate
- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
if ([animationID isEqualToString:#"showAlert"])
{
if (finished)
{
[UIView beginAnimations:nil context:nil];
self.transform = CGAffineTransformMakeScale(1.0, 1.0);
[UIView commitAnimations];
}
} else if ([animationID isEqualToString:#"hideAlert"])
{
if (finished)
{
self.transform = CGAffineTransformMakeScale(1.0, 1.0);
self.frame = originalFrame;
}
}
}
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
return YES;
}
- (BOOL)textView:(UITextView *)textViewer shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)string
{
if ([string isEqualToString:#"\n"])
{
[textViewer resignFirstResponder];
}
return [self isAcceptableTextLength:textViewer.text.length + string.length - range.length];
}
-(IBAction)checkIfCorrectLength:(id)sender
{
if (![self isAcceptableTextLength:self.textView.text.length])
{
// do something to make text shorter
}
}
- (BOOL)isAcceptableTextLength:(NSUInteger)length
{
return length <= 160;
}
- (void)textViewDidChange:(UITextView *)textViewer
{
NSString *characters = [[NSString stringWithFormat:#"%d", textViewer.text.length] stringByAppendingString:#"/160"];
NSLog(#"%#", characters);
[self updateDisplay:characters];
}
-(void) updateDisplay : (NSString *)str
{
[self.characterLimit performSelectorOnMainThread : # selector(setText : ) withObject:str waitUntilDone:YES];
}
#end
Yes, you can not present a viewcontroller from a UIView subclass.
To solve this problem, you can use your subview's superview's viewcontroller class. calling [self.superview nextResponder] in your subview will return you the superview's viewcontroller. Using that you can present your UIImagePicker view controller. To use the presentViewController method, you should cast [self.superview nextResponder] to your parentviewcontroller's class type. Also make sure you import parentview controller.h inside subview.m file
[(YourParentViewController *)[self.superview nextResponder] presentViewController:controller animated:YES completion:nil];
You should present a UIViewController subclass rather than a UIView subclass.
I would also say that UIViewController should be responsible for handling data and operational logic for its views. Check out some of the docs:
View Controller Basics:
http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/AboutViewControllers/AboutViewControllers.html
UIViewController Class Reference:
http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/AboutViewControllers/AboutViewControllers.html