2 Player setup not showing after 1 player mode is previously selected - objective-c

I'm a newbie ... I'm making a 2 player game. At the main menu, if 1 player mode is selected and then you play or go back to main menu and select 2 Player mode, the 2 player mode doesn't show the 2 player mode setup screen correctly.
If 2 player mode is selected before 1 player mode ever is, then it shows the 2 player mode setup screen fine. Below is my onePlayerViewController:
-(void)viewWillAppear:(BOOL)animated {
if ([[[NSUserDefaults standardUserDefaults] valueForKey:kGameType] isEqualToString:#"1Player"])
{
vwPlayer2.hidden=TRUE;
if (IDIOM == IPAD){
lblHeading.frame = CGRectMake(lblHeading.frame.origin.x, lblHeading.frame.origin.y+100, lblHeading.frame.size.width, lblHeading.frame.size.height);
vwCenter.frame = CGRectMake(vwCenter.frame.origin.x, vwCenter.frame.origin.y, vwCenter.frame.size.width, 644);
vwLevel.frame = CGRectMake(vwLevel.frame.origin.x,vwLevel.frame.origin.y, vwLevel.frame.size.width, vwLevel.frame.size.height);
vwPlayer1.frame = CGRectMake(vwPlayer1.frame.origin.x,vwPlayer2.frame.origin.y, vwPlayer1.frame.size.width, vwPlayer1.frame.size.height);
}else {
lblHeading.frame = CGRectMake(lblHeading.frame.origin.x, 115, lblHeading.frame.size.width, lblHeading.frame.size.height);
vwCenter.frame = CGRectMake(vwCenter.frame.origin.x, 187, vwCenter.frame.size.width, 200);
vwLevel.frame = CGRectMake(vwLevel.frame.origin.x, 105, vwLevel.frame.size.width, vwLevel.frame.size.height);
}
lblHeading.text = #"1 Player";
txtPlayerName1.text = #"Player 1";
if ([[[NSUserDefaults standardUserDefaults] valueForKey:kPlayerName1] length]!=0)
{
txtPlayerName1.text = [[NSUserDefaults standardUserDefaults] valueForKey:kPlayerName1];
}
}
else if ([[[NSUserDefaults standardUserDefaults] valueForKey:kGameType] isEqualToString:#"2Player"])
{
vwPlayer2.hidden=FALSE;
vwLevel.hidden=FALSE;
if (IDIOM == IPAD){
lblHeading.frame = CGRectMake(lblHeading.frame.origin.x, lblHeading.frame.origin.y, lblHeading.frame.size.width, lblHeading.frame.size.height);
vwCenter.frame = CGRectMake(vwCenter.frame.origin.x, vwCenter.frame.origin.y, vwCenter.frame.size.width, 644);
vwPlayer1.frame = CGRectMake(vwPlayer1.frame.origin.x,vwPlayer1.frame.origin.y, vwPlayer1.frame.size.width, vwPlayer1.frame.size.height);
vwPlayer2.frame = CGRectMake(vwPlayer2.frame.origin.x,vwPlayer2.frame.origin.y, vwPlayer2.frame.size.width, vwPlayer2.frame.size.height);
vwLevel.frame = CGRectMake(vwLevel.frame.origin.x,vwLevel.frame.origin.y, vwLevel.frame.size.width, vwLevel.frame.size.height);
}else{
if ([UIScreen mainScreen].bounds.size.height == 568)
{
lblHeading.frame = CGRectMake(lblHeading.frame.origin.x, 89, lblHeading.frame.size.width, lblHeading.frame.size.height);
vwCenter.frame = CGRectMake(vwCenter.frame.origin.x, 135, vwCenter.frame.size.width, 310);
}
else
{
lblHeading.frame = CGRectMake(lblHeading.frame.origin.x, 72, lblHeading.frame.size.width, lblHeading.frame.size.height);
vwCenter.frame = CGRectMake(vwCenter.frame.origin.x, 101, vwCenter.frame.size.width, 312);
}
}
lblHeading.text = #"2 Players";
txtPlayerName1.text = #"Player 1";
txtPlayerName2.text = #"Player 2";
if ([[[NSUserDefaults standardUserDefaults] valueForKey:kPlayerName1] length]!=0)
{
txtPlayerName1.text = [[NSUserDefaults standardUserDefaults] valueForKey:kPlayerName1];
}
if ([[[NSUserDefaults standardUserDefaults] valueForKey:kPlayerName2] length]!=0)
{
txtPlayerName2.text = [[NSUserDefaults standardUserDefaults] valueForKey:kPlayerName2];
}
}
else
{
vwPlayer2.hidden=TRUE;
vwLevel.hidden=TRUE;
if (IDIOM == IPAD){
lblHeading.frame = CGRectMake(lblHeading.frame.origin.x, lblHeading.frame.origin.y, lblHeading.frame.size.width, lblHeading.frame.size.height);
vwCenter.frame = CGRectMake(vwCenter.frame.origin.x, vwCenter.frame.origin.y, vwCenter.frame.size.width, 644);
}else{
lblHeading.frame = CGRectMake(lblHeading.frame.origin.x, 115, lblHeading.frame.size.width, lblHeading.frame.size.height);
vwCenter.frame = CGRectMake(vwCenter.frame.origin.x, 187, vwCenter.frame.size.width, 200);
}
lblHeading.text = #"Player";
txtPlayerName1.text = #"Player 1";
[[NSUserDefaults standardUserDefaults] setValue:nil forKeyPath:kPlayerName1];
[[NSUserDefaults standardUserDefaults] setValue:nil forKeyPath:kPlayerName2];
[[NSUserDefaults standardUserDefaults] setValue:nil forKey:kTurn];
if ([[[NSUserDefaults standardUserDefaults] valueForKey:kWifiPlayerName] length]!=0)
{
txtPlayerName1.text = [[NSUserDefaults standardUserDefaults] valueForKeyPath:kWifiPlayerName];
}
else
{
txtPlayerName1.text = #"Player 1";
}
}
I have tried using [[NSUserDefaults standardUserDefaults] removeObjectForKey:#"kGameType"];
[[NSUserDefaults standardUserDefaults] synchronize]; but i'm guessing that I am putting it in the wrong place??
HomeViewController -
-(void)viewWillAppear:(BOOL)animated {
if (!gameCenterEnabled)
{
[self notAnimate];
}
else
{
btnPlayer1.frame=CGRectMake(btnPlayer1.center.x, btnPlayer1.center.y, 0, 0);
btnPlayer2.frame=CGRectMake(btnPlayer2.center.x, btnPlayer2.center.y, 0, 0);
btnWifi.frame=CGRectMake(btnWifi.center.x, btnWifi.center.y, 0, 0);
btnInfo.frame=CGRectMake(btnInfo.center.x, btnInfo.center.y, 0, 0);
UILabel *lbl1 = (UILabel *)[self.view viewWithTag:1];
UILabel *lbl2 = (UILabel *)[self.view viewWithTag:2];
UILabel *lbl3 = (UILabel *)[self.view viewWithTag:3];
UILabel *lbl4 = (UILabel *)[self.view viewWithTag:4];
lbl1.alpha=1.0;
lbl2.alpha=1.0;
lbl3.alpha=1.0;
lbl4.alpha=1.0;
lbl1.frame=CGRectMake(lbl1.center.x,lbl1.center.y,0,0);
lbl2.frame=CGRectMake(lbl2.center.x,lbl2.center.y,0,0);
lbl3.frame=CGRectMake(lbl3.center.x,lbl3.center.y,0,0);
lbl4.frame=CGRectMake(lbl4.center.x,lbl4.center.y,0,0);
btnInfo.alpha = 1.0;
btnWifi.alpha = 1.0;
btnPlayer1.alpha = 1.0;
btnPlayer2.alpha = 1.0;
imgLogo.frame=CGRectMake(imgLogo.frame.origin.x, -imgLogo.frame.size.height, imgLogo.frame.size.width, imgLogo.frame.size.height);
vwBottom.frame = CGRectMake(vwBottom.frame.origin.x, self.view.frame.size.height+vwBottom.frame.size.height, vwBottom.frame.size.width, vwBottom.frame.size.height);
[self viewLoadAnimationForLogo];
[self animationOnButton];
[self animationOnLabel];
[self animationOnBottomButton];
[self.view setUserInteractionEnabled:TRUE];
}
gameCenterEnabled = YES; }
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
//Actions
-(IBAction)btnActions:(UIButton *)sender
{
NSNumber *numTag = [NSNumber numberWithInt:(int)sender.tag];
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults removeObjectForKey:kGameType];
//do this for all your keys..
[defaults synchronize];
}
self.view.userInteractionEnabled = FALSE;
switch (sender.tag)
{
//1 Player button
case 11:
[[NSUserDefaults standardUserDefaults] setValue:#"1Player" forKey:kGameType];
[UIView beginAnimations:#"animateSelection1" context:nil];
[UIView setAnimationDuration:animationDuration];
[self removeSubviewsbyAnimations];
if (IDIOM == IPAD){
[btnPlayer1 setImage:[UIImage imageNamed:#"icn1PlayerS_iPad.png"] forState:UIControlStateNormal];
}else{
[btnPlayer1 setImage:[UIImage imageNamed:#"icn1PlayerS.png"] forState:UIControlStateNormal];
}
btnPlayer2.frame=CGRectMake(btnPlayer2.center.x,btnPlayer2.center.y,0, 0);
btnWifi.frame=CGRectMake(btnWifi.center.x,btnWifi.center.y,0, 0);
btnInfo.frame=CGRectMake(btnInfo.center.x,btnInfo.center.y,0, 0);
btnPlayer1.frame=CGRectMake(btnPlayer1.frame.origin.x-btnPlayer1.frame.size.width/2, btnPlayer1.frame.origin.y-btnPlayer1.frame.size.height/2, btnPlayer1.frame.size.width*2.0, btnPlayer1.frame.size.height*2.0);
btnPlayer1.alpha = 0.0;
[UIView commitAnimations];
[self performSelector:#selector(performButtonAction:) withObject:numTag afterDelay:animationDuration];
break;
//2 Player button
case 12:
{
[[NSUserDefaults standardUserDefaults] setValue:#"2Player" forKey:kGameType];
[UIView beginAnimations:#"animateSelection2" context:nil];
[UIView setAnimationDuration:animationDuration];
[self removeSubviewsbyAnimations];
if (IDIOM == IPAD){
[btnPlayer2 setImage:[UIImage imageNamed:#"icn2PlayerS_iPad.png"] forState:UIControlStateNormal];
}else{
[btnPlayer2 setImage:[UIImage imageNamed:#"icn2PlayerS.png"] forState:UIControlStateNormal];
}
btnPlayer1.frame=CGRectMake(btnPlayer1.center.x,btnPlayer1.center.y,0, 0);
btnWifi.frame=CGRectMake(btnWifi.center.x,btnWifi.center.y,0, 0);
btnInfo.frame=CGRectMake(btnInfo.center.x,btnInfo.center.y,0, 0);
btnPlayer2.frame=CGRectMake(btnPlayer2.frame.origin.x-btnPlayer2.frame.size.width/2, btnPlayer2.frame.origin.y-btnPlayer2.frame.size.height/2, btnPlayer2.frame.size.width*2, btnPlayer2.frame.size.height*2);
btnPlayer2.alpha = 0.0;
[UIView commitAnimations];
[self performSelector:#selector(performButtonAction:) withObject:numTag afterDelay:animationDuration+0.2];
break;
}
// Wifi play button
case 13:
[[NSUserDefaults standardUserDefaults] setValue:#"WifiPlayer" forKey:kGameType];
[UIView beginAnimations:#"animateSelection3" context:nil];
[UIView setAnimationDuration:animationDuration];
[self removeSubviewsbyAnimations];
if (IDIOM == IPAD){
[btnWifi setImage:[UIImage imageNamed:#"icnWifiPlayS_iPad.png"] forState:UIControlStateNormal];
}else{
[btnWifi setImage:[UIImage imageNamed:#"icnWifiPlayS.png"] forState:UIControlStateNormal];
}
btnPlayer1.frame=CGRectMake(btnPlayer1.center.x,btnPlayer1.center.y,0, 0);
btnPlayer2.frame=CGRectMake(btnPlayer2.center.x,btnPlayer2.center.y,0, 0);
btnInfo.frame=CGRectMake(btnInfo.center.x,btnInfo.center.y,0, 0);
btnWifi.frame=CGRectMake(btnWifi.frame.origin.x-btnWifi.frame.size.width/2, btnWifi.frame.origin.y-btnWifi.frame.size.height/2, btnWifi.frame.size.width*2, btnWifi.frame.size.height*2);
btnWifi.alpha = 0.0;
[UIView commitAnimations];
[self performSelector:#selector(performButtonAction:) withObject:numTag afterDelay:animationDuration+0.2];
break;
//Info button
case 14:
[UIView beginAnimations:#"animateSelection4" context:nil];
[UIView setAnimationDuration:animationDuration];
[self removeSubviewsbyAnimations];
if (IDIOM == IPAD){
[btnInfo setImage:[UIImage imageNamed:#"icnInfoS_iPad.png"] forState:UIControlStateNormal];
}else{
[btnInfo setImage:[UIImage imageNamed:#"icnInfoS.png"] forState:UIControlStateNormal];
}
btnPlayer1.frame=CGRectMake(btnPlayer1.center.x,btnPlayer1.center.y,0, 0);
btnPlayer2.frame=CGRectMake(btnPlayer2.center.x,btnPlayer2.center.y,0, 0);
btnWifi.frame=CGRectMake(btnWifi.center.x,btnWifi.center.y,0, 0);
btnInfo.frame=CGRectMake(btnInfo.frame.origin.x-btnInfo.frame.size.width/2, btnInfo.frame.origin.y-btnInfo.frame.size.height/2, btnInfo.frame.size.width*2, btnInfo.frame.size.height*2);
btnInfo.alpha = 0.0;
[UIView commitAnimations];
[self performSelector:#selector(performButtonAction:) withObject:numTag afterDelay:animationDuration+0.2];
break;
//Setting & score button
default:
[UIView beginAnimations:#"animateSelection5" context:nil];
[UIView setAnimationDuration:animationDuration];
[self removeSubviewsbyAnimations];
btnPlayer1.frame=CGRectMake(btnPlayer1.center.x,btnPlayer1.center.y,0, 0);
btnPlayer2.frame=CGRectMake(btnPlayer2.center.x,btnPlayer2.center.y,0, 0);
btnWifi.frame=CGRectMake(btnWifi.center.x,btnWifi.center.y,0, 0);
btnInfo.frame=CGRectMake(btnInfo.center.x,btnInfo.center.y,0, 0);
[UIView commitAnimations];
[self performSelector:#selector(performButtonAction:) withObject:numTag afterDelay:animationDuration-0.1];
break;
}
}
Screenshots as I may not be very good at explaining what I mean
1 Player Mode
2 Player Mode after 1 Player Mode has been previously selected
Any advice, greatly appreciated

Related

iOS:Dispaly label with text on collectionView cell on long press

I want to display label with text on collectionViewCell on long press.
Text which i want to display is coming from array.
Following is my code:
// This code is in cellForItemAtIndexPath method
// attach long press gesture to collectionView
UILongPressGestureRecognizer *lpgr= [[UILongPressGestureRecognizer alloc]
initWithTarget:self action:#selector(handleLongPress:)];
lpgr.minimumPressDuration = .5; //seconds
lpgr.delegate = self;
[collectionViewAlbumImages addGestureRecognizer:lpgr];
lpgr.delaysTouchesBegan = YES;
-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
if (gestureRecognizer.state != UIGestureRecognizerStateEnded) {
return;
}
CGPoint p = [gestureRecognizer locationInView:collectionViewAlbumImages];
NSIndexPath *indexPath = [collectionViewAlbumImages indexPathForItemAtPoint:p];
if (indexPath == nil){
NSLog(#"couldn't find index path");
} else {
// get the cell at indexPath (the one you long pressed)
UICollectionViewCell* cell =[collectionViewAlbumImages cellForItemAtIndexPath:indexPath];
globalVariable = [GlobalBrogaard sharedInstanceMethod];
strCellImageName = [NSString stringWithFormat: #"%#",[globalVariable.arrImageName objectAtIndex:indexPath.row]];
NSLog(#"cell %f , %f",cell.frame.origin.x, cell.frame.origin.y);
// Init and add label
lblImageName = [[UILabel alloc] initWithFrame:CGRectMake(cell.frame.origin.x, cell.frame.origin.y, 200, 200)];
lblImageName.layer.cornerRadius=6;
lblImageName.clipsToBounds=NO;
lblImageName.text = strCellImageName;
[lblImageName setTextAlignment:NSTextAlignmentLeft];
lblImageName.lineBreakMode = NSLineBreakByCharWrapping;
lblImageName.numberOfLines = 0;
lblImageName.font = [UIFont systemFontOfSize:14];
lblImageName.textColor = [UIColor whiteColor];
lblImageName.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.6];
[lblImageName sizeToFit];
[cell addSubview:lblImageName];
[lblImageName setAlpha:0.0f];
//fade in
[UIView animateWithDuration:2.0f animations:^{
[lblImageName setAlpha:1.0f];
} completion:^(BOOL finished) {
//fade out
[UIView animateWithDuration:2.0f animations:^{
[lblImageName setAlpha:0.0f];
[lblImageName removeFromSuperview];
} completion:nil];
}];
}}
but issue is it works only for first collection view cell long press and on remaining cells it will not display any label.
Please tell me what is wrong in my code??
I have solved the issue by changing this line:
lblImageName = [[UILabel alloc] initWithFrame:CGRectMake(cell.frame.origin.x, cell.frame.origin.y, 200, 200)];
to:
lblImageName = [[UILabel alloc] initWithFrame:CGRectMake(0,0, 200, 200)];

First picker row selection changes second picker row

Ive picked up some code form another developer which im trying to put right. One of the problems is:
I have 2 pickers that fill a text box with selected row from a picker.
If picker 1 (named: Type) is selected, the row selected ..say row 3, defaults to that row on my next picker (named: FlueType) when the picker is presented.
How can I get the second picker not be affected by the first pickers row selection?
Ive looked at [picker reloadComponent:0]; I've looked on stack and google and cant seem to find anything that fits this problem.
Ive also tried [picker selectRow:0 inComponent:0 animated:NO] in the ViewDidLoad method hoping that it would set all my pickers to the first row value which is all im trying to do.
Apologies for the mountain of code, I've tried to separate it out into context
/////////////////////picker action////////////////////////
-(void)flueTypeBtnClicked//:(id)sender
{
[flueTypeBtn.titleLabel setTextColor:[UIColor blackColor]];
currentSelectedIndex = flueTypeBtn.tag;
[makeTxt resignFirstResponder];
[modelTxt resignFirstResponder];
[locationTxt resignFirstResponder];
[oprPressureMBarTxt resignFirstResponder];
[picker setHidden:NO];
[picker reloadComponent:0];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.3];
self.ToolsView.frame = CGRectMake(0, 200, 320, 260);
extern GasCertificateAppViewController *viewController;
[viewController.view addSubview:self.ToolsView];
[UIView commitAnimations];
}
-(void)typeBtnClicked//:(id)sender
{
[typeBtn.titleLabel setTextColor:[UIColor blackColor]];
currentSelectedIndex = typeBtn.tag;
[makeTxt resignFirstResponder];
[modelTxt resignFirstResponder];
[locationTxt resignFirstResponder];
[oprPressureMBarTxt resignFirstResponder];
[picker setHidden:NO];
[picker reloadComponent:0];
//NSLog(#"In type btn Clicked:");
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.3];
self.ToolsView.frame = CGRectMake(0, 200, 320, 260);
extern GasCertificateAppViewController *viewController;
[viewController.view addSubview:self.ToolsView];
[UIView commitAnimations];
///////////////////////////////////////////////////////////////////////////////////////////////////////////////more code here///////////////////////
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
if (textField.tag == 1 )
{
[self typeBtnClicked];
return NO;
}
else if(textField.tag == 3)
{
[self flueTypeBtnClicked];
return NO;
}
CGPoint offset = CGPointMake(0, textField.frame.origin.y - textField.frame.size.height);
[self.screenScrollView setContentOffset: offset animated: YES];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.3];
self.ToolsView.frame = CGRectMake(0, 200, 320, 260);
extern GasCertificateAppViewController *viewController;
[viewController.view addSubview:self.ToolsView];
[UIView commitAnimations];
return YES;
}
//////////////
-(void) fillData
{
extern Survey *survey;
ApplianceTest *test = [survey.applianceTestArray objectAtIndex:testId];
if(test.type != nil)
[self.typeTxt setText:test.type];
// [self.typeBtn setTitle:test.type forState:UIControlStateNormal];
if(test.make != nil)
[self.makeTxt setText:test.make];
if(test.model != nil)
[self.modelTxt setText:test.model];
if(test.location != nil)
[self.locationTxt setText:test.location];
if(test.flue_type != nil)
[self.flueTypeTxt setText:test.flue_type];
//[self.flueTypeBtn setTitle:test.flue_type forState:UIControlStateNormal]; if(test.operating_pressure_mbar_or_heat_input_kwh != nil)
[self.oprPressureMBarTxt setText:test.operating_pressure_mbar_or_heat_input_kwh];
if([test.safety_device_correct isEqualToString:#"Yes"])
[self.segtCtrl setSelectedSegmentIndex:0];
else
if([test.safety_device_correct isEqualToString:#"No"])
[self.segtCtrl setSelectedSegmentIndex:1];
else
[self.segtCtrl setSelectedSegmentIndex:2];
}
-(IBAction)bgTouched:(id)sender
{
CGPoint offset = CGPointMake(0, 0);
[self.screenScrollView setContentOffset: offset animated: YES];[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.3];
self.ToolsView.frame = CGRectMake(0, 500, 320,260);
//[self.ToolsView removeFromSuperview];
//self.view.frame = CGRectMake(0, 0, 320, 372 );
[makeTxt resignFirstResponder];
[modelTxt resignFirstResponder];
[locationTxt resignFirstResponder];
[oprPressureMBarTxt resignFirstResponder];
[UIView commitAnimations];
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)viewDidLoad {
[super viewDidLoad];
//segment control selected Index = 2;
segtCtrl.selectedSegmentIndex = 2;
navigationTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(130, 0, 200, 25)];
navigationTitleLabel.textAlignment = UITextAlignmentCenter;
navigationTitleLabel.font= [UIFont fontWithName:#"Futura" size:18];
navigationTitleLabel.backgroundColor = [UIColor clearColor];
navigationTitleLabel.textColor = [UIColor whiteColor];
navigationTitleLabel.text = #"Appliance Test 1/3";
self.navigationItem.titleView = navigationTitleLabel;
self.screenScrollView.frame = CGRectMake(0, 0, 320, 370);
self.screenScrollView.contentSize = CGSizeMake(320, 600 + 200);
self.screenScrollView.clipsToBounds = YES;
self.screenScrollView.showsVerticalScrollIndicator = NO;
[self.view addSubview:self.screenScrollView];
testId = [testIdStr intValue];
currentSelectedIndex = 0;
typeArray = [[NSMutableArray alloc] init];
[typeArray addObject:#""]; ///change
[typeArray addObject:#"Boiler"];
[typeArray addObject:#"Cooker"];
[typeArray addObject:#"Fire"];
[typeArray addObject:#"Hob"]; ///change to hob
currentSelectedIndex = 0;
flueTypeArray = [[NSMutableArray alloc] init];
[flueTypeArray addObject:#""]; //change
[flueTypeArray addObject:#"OF"];
[flueTypeArray addObject:#"RS"];
[flueTypeArray addObject:#"FL"];
unitArray = [[NSMutableArray alloc] initWithObjects:#"MBar",#"KW/h",nil];
//self.navigationItem.title = #"Appliance Test 1/3";
//[typeTableView setHidden:YES];
//[flueTypeTableView setHidden:YES];
[segtCtrl setSelectedSegmentIndex:2];
extern Survey *survey;
[self fillData];
[picker setHidden:YES];
self.ToolsView.frame = CGRectMake(0, 500, 320, 260);
/////////////////
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent: (NSInteger)component
{
if (currentSelectedIndex == 1)
{
return [typeArray count];
}
else if(currentSelectedIndex == 3)
{
return [flueTypeArray count];
}
else if(currentSelectedIndex == 7)
{
return [unitArray count];
}
else
{
return 1;
}
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
if (currentSelectedIndex == 1)
{
if ([typeArray count] == 0)
{
return [NSString stringWithFormat: #"None"];
}
else
{
return [typeArray objectAtIndex:row];
}
}
else if(currentSelectedIndex == 3)
{
if ([flueTypeArray count] == 0)
{
return [NSString stringWithFormat: #"None"];
}
else {
return [flueTypeArray objectAtIndex:row];
}
}
else if(currentSelectedIndex == 7)
{
if ([unitArray count] == 0)
{
return [NSString stringWithFormat: #"None"];
}
else
{
return [unitArray objectAtIndex:row];
}
}
return #"";
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
// [gasSafeNoBtn setTitle:[NSString stringWithFormat:#"%d",[(NSNumber *) [gasSafeNoArray objectAtIndex:row]intValue]] forState:UIControlStateNormal];
extern Survey *survey;
if (currentSelectedIndex==1)
{
//typeTxt.text = [typeArray objectAtIndex:row];
[typeBtn.titleLabel setTextColor:[UIColor blackColor]];
[typeBtn setTitle:[typeArray objectAtIndex:row] forState:UIControlStateNormal];
typeTxt.text =[typeArray objectAtIndex:row] ;
}
else if(currentSelectedIndex == 3)
{
//flueTypeTxt.text = [flueTypeArray objectAtIndex:row];
[flueTypeBtn.titleLabel setTextColor:[UIColor blackColor]];
[flueTypeBtn setTitle:[flueTypeArray objectAtIndex:row] forState:UIControlStateNormal];
flueTypeTxt.text= [flueTypeArray objectAtIndex:row];
}
else if(currentSelectedIndex == 7)
{
unitString = [[NSString alloc] initWithString:[unitArray objectAtIndex:row]];
// NSLog(#"Unit String : %#", unitString);
[unitBtn setTitle:[unitArray objectAtIndex:row] forState:UIControlStateNormal];
}
else {
}
}
- (void)dealloc {
[unitArray release];
[ToolsView release];
[toolBar release];
[nextBtn release];
[prevBtn release];
[doneBtn release];
[picker release];
[super dealloc];
}
#end
Ok sorted....added
[picker selectRow:0 inComponent:0 animated:NO];
to the button action method presenting the picker

Issue in previewing the video using AVFoundation and MPMovieController at a time in iphone sdk

I am Using AVFoundation's AVCaptureSession to capture the video and I am using the MPMoviePlayerController to play the streamed url(video) from server. When I am capturing only video with AVCaptureSession there is no problem. But When I tried to play the streamed url(with MPMoviePlayerController) along with capturing of video with AVCaptureSession at a time the problem occurs as the capturing from AVCaptureSession stops.
This is what I had done:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication ]delegate];
if([appDelegate isIpad] == YES)
controlsView = [[UIView alloc] initWithFrame:CGRectMake(self.view.bounds.origin.x+200, self.view.bounds.origin.y+250, self.view.bounds.size.width, self.view.bounds.size.height)];
else
controlsView = [[UIView alloc] initWithFrame:self.view.bounds];
controlsView.backgroundColor = [UIColor blackColor];
[self.view addSubview:controlsView];
[self.view sendSubviewToBack:controlsView];
//settingsBtn = [[UIButton alloc]initWithFrame:CGRectMake(10,400, 50, 50)];
settingsBtn = [[UIButton alloc]initWithFrame:CGRectMake(10,400, 50, 50)];
[settingsBtn setImage:[UIImage imageNamed:#"settings.png"] forState:UIControlStateNormal];
[settingsBtn addTarget:self action:#selector(settingsAction) forControlEvents:UIControlEventTouchUpInside];
[controlsView addSubview:settingsBtn];
callButton = [[UIButton alloc]initWithFrame:CGRectMake(260,400, 50, 50)];
if(isCallButtonClicked ==NO)
[callButton setImage:[UIImage imageNamed:#"call.png"] forState:UIControlStateNormal];
else
[callButton setImage:[UIImage imageNamed:#"callEnd.png"] forState:UIControlStateNormal];
[callButton addTarget:self action:#selector(callAction) forControlEvents:UIControlEventTouchUpInside];
[controlsView addSubview:callButton];
statusLabel = [[UILabel alloc]initWithFrame:CGRectMake(120, 20, 150, 40)];
statusLabel.textColor = [UIColor whiteColor];
statusLabel.backgroundColor = [UIColor clearColor];
statusLabel.textAlignment = UITextAlignmentLeft;
statusLabel.font = [UIFont boldSystemFontOfSize:20];
dot1 = [[UIView alloc] initWithFrame:CGRectMake(75, 20, 7, 7)];
dot1.layer.cornerRadius = 5;
dot1.backgroundColor = [UIColor whiteColor];
[statusLabel addSubview:dot1];
dot2 = [[UIView alloc] initWithFrame:CGRectMake(84, 20, 7, 7)];
dot2.layer.cornerRadius = 5;
dot2.backgroundColor = [UIColor whiteColor];
[statusLabel addSubview:dot2];
dot3 = [[UIView alloc] initWithFrame:CGRectMake(93, 20, 7, 7)];
dot3.layer.cornerRadius = 5;
dot3.backgroundColor = [UIColor whiteColor];
[statusLabel addSubview:dot3];
downStreamView = [[UIView alloc]initWithFrame:CGRectMake(controlsView.bounds.origin.x, controlsView.bounds.origin.y, controlsView.bounds.size.width, controlsView.bounds.size.height - 70)];
[[controlsView layer] addSublayer:downStreamView.layer];
downStreamView.layer.backgroundColor = [UIColor greenColor].CGColor;
AVCaptureSession *captureSession = [[AVCaptureSession alloc]init];
NSError *error;
/* getting the device input */
AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:[self frontFacingCamera] error:&error];
if(error)
{
NSLog(#"%#",#"Could not create video input");
}
[captureSession addInput:videoInput];
AVCaptureDeviceInput *audioInput = [AVCaptureDeviceInput deviceInputWithDevice:[self audioDevice] error:&error];
[captureSession addInput:audioInput];
audioOutput = [[AVCaptureAudioDataOutput alloc]init];
[captureSession addOutput:audioOutput];
previewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:captureSession];
[previewLayer setFrame:CGRectMake(controlsView.bounds.origin.x, controlsView.bounds.origin.y, controlsView.bounds.size.width, controlsView.bounds.size.height - 70)];
[previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[[controlsView layer] addSublayer:previewLayer];
[captureSession startRunning];
}
//make call Action
-(void)makeCallAction
{
if(isCallButtonClicked == NO)
{
statusLabel.text = #"Dialling";
[controlsView addSubview:statusLabel];
if(!isAnimationStarted)
[self animate];
[callButton setImage:[UIImage imageNamed:#"callEnd.png"] forState:UIControlStateNormal];
[UIView animateWithDuration:2.0
animations:^{
CGRect frame = CGRectMake(downStreamView.layer.bounds.origin.x, downStreamView.layer.bounds.size.height-100, 100, 100);
previewLayer.frame = frame;
[downStreamView.layer addSublayer:previewLayer];
}
completion:^(BOOL finished){
//Do nothing
}];
isCallButtonClicked = YES;
}
else if(isCallButtonClicked == YES)
{
[statusLabel removeFromSuperview];
[callButton setImage:[UIImage imageNamed:#"call.png"] forState:UIControlStateNormal];
[UIView animateWithDuration:2.0
animations:^{
[previewLayer setFrame:CGRectMake(controlsView.bounds.origin.x, controlsView.bounds.origin.y, controlsView.bounds.size.width, controlsView.bounds.size.height - 70)];
[[controlsView layer] addSublayer:previewLayer];
}
completion:^(BOOL finished){
//Do nothing
}];
isCallButtonClicked = NO;
}
}
//Settings Action
-(void)settingsAction
{
NSString *nibName = nil;
if ([[[UIDevice currentDevice] model] isEqualToString:#"iPhone"] || [[[UIDevice currentDevice] model] isEqualToString:#"iPhone Simulator"]) {
nibName = #"SettingsViewController";
}
else {
nibName = #"SettingsViewController_iPad";
}
SettingsViewController *settingsController = [[SettingsViewController alloc]initWithNibName:nibName bundle:nil];
[self.navigationController presentModalViewController:settingsController animated:YES];
}
-(void)callAction
{
NSURL *theMovieURL = [NSURL URLWithString:#"someURL.m3u8"];
if (theMovieURL)
{
if ([theMovieURL scheme]) // sanity check on the URL
{
/* Play the movie with the specified URL. */
[self playStreamingURL:theMovieURL];
}
}
[self makeCallAction];
}
-(void)playStreamingURL:(NSURL *)aUrlStr
{
MPMovieSourceType movieSourceType = MPMovieSourceTypeUnknown;
/* If we have a streaming url then specify the movie source type. */
if ([[aUrlStr pathExtension] compare:#"m3u8" options:NSCaseInsensitiveSearch] == NSOrderedSame)
{
movieSourceType = MPMovieSourceTypeStreaming;
}
[self createAndPlayMovieForURL:aUrlStr sourceType:movieSourceType];
}
-(void)createAndPlayMovieForURL:(NSURL *)movieURL sourceType:(MPMovieSourceType)sourceType
{
[self createAndConfigurePlayerWithURL:movieURL sourceType:sourceType];
/* making the player to be visible in full screen mode */
//if(!self.moviePlayerController.fullscreen)
// self.moviePlayerController.fullscreen = YES;
/* disabling the controls of the movie player */
self.moviePlayerController.controlStyle = MPMovieControlStyleNone;
/* Play the movie! */
[[self moviePlayerController] play];
}
-(void)createAndConfigurePlayerWithURL:(NSURL *)movieURL sourceType:(MPMovieSourceType)sourceType
{
[controlsView addSubview:downStreamView];
/* Create a new movie player object. */
MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
if (player)
{
/* Save the movie object. */
[self setMoviePlayerController:player];
player.contentURL = MPMovieControlStyleNone;
//if(!player.fullscreen)
// player.fullscreen = YES;
/* Register the current object as an observer for the movie
notifications. */
// [self installMovieNotificationObservers];
/* Specify the URL that points to the movie file. */
[player setContentURL:movieURL];
/* If you specify the movie type before playing the movie it can result
in faster load times. */
[player setMovieSourceType:sourceType];
/* Apply the user movie preference settings to the movie player object. */
//[self applyUserSettingsToMoviePlayer];
/* Add a background view as a subview to hide our other view controls
underneath during movie playback. */
//CGRect viewInsetRect = CGRectInset ([self.view bounds],
// kMovieViewOffsetX,
//kMovieViewOffsetY );
/* Inset the movie frame in the parent view frame. */
[[player view] setFrame:downStreamView.bounds];
[player view].backgroundColor = [UIColor redColor];
/* To present a movie in your application, incorporate the view contained
in a movie player’s view property into your application’s view hierarchy.
Be sure to size the frame correctly. */
[downStreamView.layer addSublayer: [player view].layer];
}
}
-(void)installMovieNotificationObservers
{
MPMoviePlayerController *player = [self moviePlayerController];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(loadStateDidChange:)
name:MPMoviePlayerLoadStateDidChangeNotification
object:player];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayBackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:player];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(mediaIsPreparedToPlayDidChange:)
name:MPMediaPlaybackIsPreparedToPlayDidChangeNotification
object:player];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayBackStateDidChange:)
name:MPMoviePlayerPlaybackStateDidChangeNotification
object:player];
}
/* Notification called when the movie finished playing. */
- (void) moviePlayBackDidFinish:(NSNotification*)notification
{
NSNumber *reason = [[notification userInfo] objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey];
switch ([reason integerValue])
{
/* The end of the movie was reached. */
case MPMovieFinishReasonPlaybackEnded:
/*
Add your code here to handle MPMovieFinishReasonPlaybackEnded.
*/
break;
/* An error was encountered during playback. */
case MPMovieFinishReasonPlaybackError:
NSLog(#"An error was encountered during playback");
[self performSelectorOnMainThread:#selector(displayError:) withObject:[[notification userInfo] objectForKey:#"error"] waitUntilDone:NO];
[self removeMovieViewFromViewHierarchy];
break;
/* The user stopped playback. */
case MPMovieFinishReasonUserExited:
[self removeMovieViewFromViewHierarchy];
break;
default:
break;
}
}
/* Remove the movie view from the view hierarchy. */
-(void)removeMovieViewFromViewHierarchy
{
MPMoviePlayerController *player = [self moviePlayerController];
[player.view removeFromSuperview];
}
- (void)animate {
isAnimationStarted = YES;
//First Animation
[UIView animateWithDuration:0.5 animations:^{
dot1.alpha = 1;
dot2.alpha = 0.5;
dot3.alpha = 0.5;
} completion:^(BOOL finished) {
//2nd Animation
[UIView animateWithDuration:0.5 animations:^{
dot1.alpha = 0.5;
dot2.alpha = 1;
dot3.alpha = 0.5;
} completion:^(BOOL finished) {
//3rd Animation
[UIView animateWithDuration:0.5 animations:^{
dot1.alpha = 0.5;
dot2.alpha = 0.5;
dot3.alpha = 1;
} completion:^(BOOL finished) {
[self performSelector:#selector(animate)];
}];
}];
}];
}
// Find a camera with the specificed AVCaptureDevicePosition, returning nil if one is not found
- (AVCaptureDevice *) cameraWithPosition:(AVCaptureDevicePosition) position
{
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for (AVCaptureDevice *device in devices) {
if ([device position] == position) {
return device;
}
}
return nil;
}
// Find a front facing camera, returning nil if one is not found
- (AVCaptureDevice *) frontFacingCamera
{
return [self cameraWithPosition:AVCaptureDevicePositionFront];
}
// Find a back facing camera, returning nil if one is not found
- (AVCaptureDevice *) backFacingCamera
{
return [self cameraWithPosition:AVCaptureDevicePositionBack];
}
- (AVCaptureDevice *) audioDevice
{
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
if ([devices count] > 0) {
return [devices objectAtIndex:0];
}
return nil;
}
-(void)audioData:(id)info
{
NSArray *connections = audioOutput.connections;
AVCaptureConnection *connection = [connections objectAtIndex:0];
NSArray *audioChannels = connection.audioChannels;
AVCaptureAudioChannel *audioChannel = [audioChannels objectAtIndex:0];
//[label setText:[NSString stringWithFormat:#"%f", audioChannel.averagePowerLevel]];
}
Guy's Please help me how to resolve this issue :(
Regards

How to copy cells between tables as the pulse app

I need to copy cells between 2 table views.
I have a more-or-less working solution. However, it is not smooth, and I would love to do something similar to the pulse app reorder feeds option...
Something special in the way that pulse works, is that the reorder animation is the same as in a normal reorder of cells, but still the cell can move between tables.
This is what I have now:
- (BoardColumnView *) addColumn:(NSString *)title type:(ColumnType)type{
BoardColumnView *col = [BoardColumnView createColumn:title];
[self.columns addObject:col];
// Add a pinch gesture recognizer to the table view.
UILongPressGestureRecognizer* draggingRecognizer = [[UILongPressGestureRecognizer alloc]
initWithTarget:self
action:#selector(moveActionGestureRecognizerStateChanged:)
];
draggingRecognizer.minimumPressDuration = 0.5;
draggingRecognizer.delegate = self;
[col.tableView addGestureRecognizer:draggingRecognizer];
[draggingRecognizer release];
return col;
}
#pragma mark -
#pragma mark UIGestureRecognizer Delegate/Actions
- (BOOL) gestureRecognizerShouldBegin: (UIGestureRecognizer *) gestureRecognizer
{
ALog(#"Drag detected");
return YES;
}
- (void) moveActionGestureRecognizerStateChanged: (UIGestureRecognizer *) recognizer
{
switch ( recognizer.state )
{
default:
case UIGestureRecognizerStateFailed:
// do nothing
break;
case UIGestureRecognizerStatePossible:
case UIGestureRecognizerStateCancelled:
{
ALog(#"Canceled");
[UIView beginAnimations: #"SnapBack" context: NULL];
[UIView setAnimationCurve: UIViewAnimationCurveEaseOut];
[UIView setAnimationDuration: 0.5];
[UIView setAnimationDelegate: self];
[UIView setAnimationDidStopSelector: #selector(finishedSnap:finished:context:)];
CGRect f = self.dragView.frame;
f.origin = _dragOriginCellOrigin;
self.dragView.frame = f;
[UIView commitAnimations];
break;
}
case UIGestureRecognizerStateEnded:
{
// move the real cell into place
[UIView beginAnimations: #"SnapToPlace" context: NULL];
[UIView setAnimationCurve: UIViewAnimationCurveEaseOut];
[UIView setAnimationDuration: 0.5];
[UIView setAnimationDelegate: self];
[UIView setAnimationDidStopSelector: #selector(finishedSnap:finished:context:)];
CGRect r = self.dragView.frame;//[self.content rectForItemAtIndex: _emptyCellIndex];
CGRect f = self.dragView.frame;
f.origin.x = r.origin.x + floorf((r.size.width - f.size.width) * 0.5);
f.origin.y = r.origin.y + floorf((r.size.height - f.size.height) * 0.5);
NSLog( #"Gesture ended-- moving to %#", NSStringFromCGRect(f) );
self.dragView.frame = f;
self.dragView.transform = CGAffineTransformIdentity;
self.dragView.alpha = 1.0;
[UIView commitAnimations];
break;
}
case UIGestureRecognizerStateBegan:
{
ALog(#"Start move..");
// find the cell at the current point and copy it into our main view, applying some transforms
_lastColumn = (BoardColumnView *)[(UITableView *)recognizer.view superview];
_targetColumn = _lastColumn;
if (_lastIndexPath) {
[_lastIndexPath release];
_lastIndexPath = nil;
}
_lastIndexPath = [_lastColumn.tableView indexPathForRowAtPoint:[recognizer locationInView: _lastColumn]];
UITableViewCell *sourceCell = [_lastColumn.tableView cellForRowAtIndexPath:_lastIndexPath];
CGRect frame = [_lastColumn convertRect: sourceCell.frame fromView: self.content];
self.dragView = [[[UIImageView alloc] initWithImage:[sourceCell screenshot]] autorelease];
self.dragView.opaque = YES;
self.dragView.backgroundColor = _lastColumn.backgroundColor;
self.dragView.center = [recognizer locationInView: self.view];
//self.dragView.cornerRadius = 8; // if you like rounded corners
self.dragView.layer.shadowOffset = CGSizeMake(-5, 2);
self.dragView.layer.shadowRadius = 5;
self.dragView.layer.shadowOpacity = 0.5;
[content addSubview: self.dragView];
[content bringSubviewToFront:self.dragView];
// grab some info about the origin of this cell
_dragOriginCellOrigin = frame.origin;
[UIView beginAnimations: #"" context: NULL];
[UIView setAnimationDuration: 0.2];
[UIView setAnimationCurve: UIViewAnimationCurveEaseOut];
// transformation-- larger, slightly transparent
self.dragView.transform = CGAffineTransformMakeScale( 1.2, 1.2 );
self.dragView.alpha = 0.7;
[UIView commitAnimations];
/* // reload the grid underneath to get the empty cell in place
[self.content reloadItemsAtIndices: [NSIndexSet indexSetWithIndex: index]
withAnimation: AQGridViewItemAnimationNone];
*/
break;
}
case UIGestureRecognizerStateChanged:
{
// update draging cell location
self.dragView.center = [recognizer locationInView: self.view];
//Determinar sobre que columna esta flotando..
CGRect global;
if (_targetColumn) {
_targetColumn = nil;
}
for (BoardColumnView *col in self.columns) {
UITableView *table = col.tableView;
global = [table convertRect:self.dragView.frame fromView:content];
if ([table pointInside:global.origin withEvent:nil]) {
ALog([NSString stringWithFormat: #"Esta sobre la tabla %#", col.column.name]);
_targetColumn = col;
break;
}
}
if ( !_targetColumn )
{
ALog(#"Esta en zona muerta");
}
break;
}
}
}
- (void) finishedSnap: (NSString *) animationID finished: (NSNumber *) finished context: (void *) context
{
if (_targetColumn && _lastIndexPath) {
ALog(#"Moviendo a nuevo destino");
CGRect frame = [_targetColumn convertRect: self.dragView.frame fromView: self.content];
NSIndexPath *destPath = [_targetColumn.tableView indexPathForRowAtPoint: frame.origin];
[UIView beginAnimations: #"" context: NULL];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:#selector(animationDidStop:finished:context:)];
self.dragView.backgroundColor = _targetColumn.backgroundColor;
//Si inserta entre tareas en destino...
_lastColumn.totalRows -= 1;
_targetColumn.totalRows += 1;
[_lastColumn.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:_lastIndexPath] withRowAnimation:UITableViewRowAnimationTop];
if (destPath) {
[_targetColumn.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:destPath] withRowAnimation:UITableViewRowAnimationBottom];
} else {
[_targetColumn.tableView reloadData];
}
[UIView commitAnimations];
} else {
ALog(#"Cancelado el moviento, regresar a home");
UITableViewCell * sourceCell = [_lastColumn.tableView cellForRowAtIndexPath:_lastIndexPath];
if (sourceCell) {
[UIView beginAnimations: #"Back" context: NULL];
[UIView setAnimationCurve: UIViewAnimationCurveEaseOut];
[UIView setAnimationDuration: 0.5];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:#selector(animationDidStop:finished:context:)];
//self.dragView.transform = CGAffineTransformIdentity;
self.dragView.frame = [self.content convertRect: sourceCell.frame fromView: _lastColumn];
//self.dragView.alpha = 0.0;
[UIView commitAnimations];
}
}
}
- (void)animationDidStop:(id)animationID finished:(BOOL)flag context:(id)context {
// dismiss our copy of the cell
ALog(#"Eliminando drag view");
[self.dragView removeFromSuperview];
self.dragView = nil;
_lastColumn = nil;
_targetColumn = nil;
if (_lastIndexPath) {
_lastIndexPath = nil;
}
}
UPDATE: I've created an open source project to show my progress so far:
https://bitbucket.org/elmalabarista/dragdroptableviews

Photo gallery functionality

I need to simulate the photo gallery effects.
I have uiimageview, I need to zoom in and out, scale and - if I double tapped (or shook the iPad - I want the image to return to its actual size.
I tried a lot, but all the available examples are buggy and not complete; I don't want to use uiwebview.
Any suggestion, please?
here's the code
in view did load
:
holderView = [[UIView alloc] initWithFrame:CGRectMake(0,0,self.view.bounds.size.width,self.view.bounds.size.height)];
imageview = [[UIImageView alloc] initWithFrame:[holderView frame]];
[imageview setImage:myimage];
imageview.contentMode = UIViewContentModeScaleAspectFit;
//holderView.contentMode = UIViewContentModeScaleAspectFit ;
[holderView addSubview:imageview];
UIPinchGestureRecognizer *pinchRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:#selector(scale:)];
[pinchRecognizer setDelegate:self];
[holderView addGestureRecognizer:pinchRecognizer];
UIRotationGestureRecognizer *rotationRecognizer = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:#selector(rotate:)];
[rotationRecognizer setDelegate:self];
[holderView addGestureRecognizer:rotationRecognizer];
UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(move:)];
[panRecognizer setMinimumNumberOfTouches:1];
[panRecognizer setMaximumNumberOfTouches:1];
[panRecognizer setDelegate:self];
[holderView addGestureRecognizer:panRecognizer];
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tapped:)];
[tapRecognizer setNumberOfTapsRequired:1];
[tapRecognizer setDelegate:self];
[holderView addGestureRecognizer:tapRecognizer];
and the following is the code I use for the functions
-(void)scale:(id)sender {
[self.view bringSubviewToFront:[(UIPinchGestureRecognizer*)sender view]];
if(zooming)
{
if([(UIPinchGestureRecognizer*)sender state] == UIGestureRecognizerStateEnded) {
lastScale = 1.0;
return;
}
CGFloat scale = 1.0 - (lastScale - [(UIPinchGestureRecognizer*)sender scale]);
CGAffineTransform currentTransform = [(UIPinchGestureRecognizer*)sender view].transform;
CGAffineTransform newTransform = CGAffineTransformScale(currentTransform, scale, scale);
[[(UIPinchGestureRecognizer*)sender view] setTransform:newTransform];
lastScale = [(UIPinchGestureRecognizer*)sender scale];
OldTransform = newTransform;
OldCenter = [(UIPinchGestureRecognizer*)sender view].center;
Does_Panned = YES ;
Does_transformed = YES ;
}
else {
}
}
-(void)rotate:(id)sender {
if(zooming)
{
[self.view bringSubviewToFront:[(UIRotationGestureRecognizer*)sender view]];
if([(UIRotationGestureRecognizer*)sender state] == UIGestureRecognizerStateEnded) {
lastRotation = 0.0;
return;
}
CGFloat rotation = 0.0 - (lastRotation - [(UIRotationGestureRecognizer*)sender rotation]);
CGAffineTransform currentTransform = [(UIPinchGestureRecognizer*)sender view].transform;
CGAffineTransform newTransform = CGAffineTransformRotate(currentTransform,rotation);
[[(UIRotationGestureRecognizer*)sender view] setTransform:newTransform];
lastRotation = [(UIRotationGestureRecognizer*)sender rotation];
OldTransform = newTransform ;
OldCenter = [(UIPinchGestureRecognizer*)sender view].center;
Does_Panned = YES ;
Does_transformed = YES ;
}
}
-(void)move:(id)sender {
if(zooming)
{
[[[(UITapGestureRecognizer*)sender view] layer] removeAllAnimations];
[self.view bringSubviewToFront:[(UIPanGestureRecognizer*)sender view]];
CGPoint translatedPoint = [(UIPanGestureRecognizer*)sender translationInView:self.view];
if([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateBegan) {
firstX = [[sender view] center].x;
firstY = [[sender view] center].y;
}
translatedPoint = CGPointMake(firstX+translatedPoint.x, firstY+translatedPoint.y);
[[sender view] setCenter:translatedPoint];
OldCenter = translatedPoint ;
Does_Panned = YES ;
Does_transformed = NO ;
if([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateEnded) {
CGFloat finalX = translatedPoint.x + (.35*[(UIPanGestureRecognizer*)sender velocityInView:self.view].x);
CGFloat finalY = translatedPoint.y + (.35*[(UIPanGestureRecognizer*)sender velocityInView:self.view].y);
if(UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation])) {
if(finalX < 0) {
finalX = 0;
}
else if(finalX > 768) {
finalX = 768;
}
if(finalY < 0) {
finalY = 0;
}
else if(finalY > 1024) {
finalY = 1024;
}
}
else {
if(finalX < 0) {
finalX = 0;
}
else if(finalX > 1024) {
finalX = 768;
}
if(finalY < 0) {
finalY = 0;
}
else if(finalY > 768) {
finalY = 1024;
}
}
[UIView beginAnimations:nil context:NULL];
//[UIView setAnimationDelay: 1.0];
[UIView setAnimationDuration:.20];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
//[[sender view] setCenter:CGPointMake(finalX, finalY)];
[UIView commitAnimations];
}
}
else{
if([(UIPanGestureRecognizer*)sender maximumNumberOfTouches] == 1)
{
UIPanGestureRecognizer* recognize = (UIPanGestureRecognizer*)sender;
//change the current window width and level
if([recognize state] == UIGestureRecognizerStateBegan) {
Bigen =[recognize translationInView:recognize.view ];// [[sender view] center];
BeginX = Bigen.x;
BeginY = Bigen.y;
}
else if(
( [recognize state] == UIGestureRecognizerStateChanged )||
(recognize.state == UIGestureRecognizerStateEnded) )
{
CGPoint translation = [recognize translationInView:recognize.view ];
End = translation ;
EndX = End.x ;
EndY = End.y ;
double offsetw=0;
double offsetl=0;
if(EndX>BeginX)
{
offsetw=50*(EndX-BeginX);
}
else if(EndX<BeginX)
{
offsetw=50*(EndX-BeginX);
}
else
{
offsetw=0;
}
if(EndY>BeginY)
{
offsetl=50*(EndY-BeginY);
}
else if(EndY<BeginY)
{
offsetl=50*(EndY-BeginY);
}
else
{
offsetl=0;
}
ChangeWW_Wl(offsetw, offsetl);
[self AddImage];
}
//if([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateEnded) {
/* CGPoint translatedPoint = [(UIPanGestureRecognizer*)sender translationInView:self.view];
EndX = translatedPoint.x;
EndY = translatedPoint.y;*/
//}
}
}
}
(void)tapped:(id)sender {
if(zooming)
{
[[[(UITapGestureRecognizer*)sender view] layer] removeAllAnimations];
}
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
return ![gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]];
}
how to update it to reset the image to its original size at shaking or double tap
how to over come the improper zooming (zoom with large factor at the first time )
You should watch the "Designing Apps with Scroll Views" video from WWDC2010, it tells you how to do this exact thing.