Using Existing Segmented Control to Control mkmapkit zoom - iphone

I have a segmented control which controls the address and phone number as well as some other labels on a screen.
I am trying to also get this same control to zoom into the specific location of three locations on the mkmapview and make the zoom level at street view depending what button they push. Any help would be appreciated.
Here is my .m file:
#implementation LocationInfoViewController;
#synthesize mapView;
-(void)viewDidLoad
{
[super viewDidLoad];
[mapView setMapType:MKMapTypeStandard];
[mapView setZoomEnabled:YES];
[mapView setScrollEnabled:YES];
[mapView setDelegate:self];
MKCoordinateRegion morristown = { {0.0, 0.0} , {0.0, 0.0} };
morristown.center.latitude = 40.797011;
morristown.center.longitude = -74.482855;
morristown.span.longitudeDelta = 0.60f;
morristown.span.latitudeDelta = 0.60f;
[mapView setRegion:morristown animated:YES];
Annotation *ann1 = [[Annotation alloc] init];
ann1.title = #"Sushi Lounge";
ann1.subtitle = #"Morristown";
ann1.coordinate = morristown.center;
[mapView addAnnotation: ann1];
MKCoordinateRegion hoboken = { {0.0, 0.0} , {0.0, 0.0} };
hoboken.center.latitude = 40.738496;
hoboken.center.longitude = -74.029434;
hoboken.span.longitudeDelta = 0.60f;
hoboken.span.latitudeDelta = 0.60f;
[mapView setRegion:hoboken animated:YES];
Annotation *ann2 = [[Annotation alloc] init];
ann2.title = #"Sushi Lounge";
ann2.subtitle = #"Hoboken";
ann2.coordinate = hoboken.center;
[mapView addAnnotation:ann2];
MKCoordinateRegion totawa = { {0.0, 0.0} , {0.0, 0.0} };
totawa.center.latitude = 40.875682;
totawa.center.longitude = -74.301787;
totawa.span.longitudeDelta = 0.60f;
totawa.span.latitudeDelta = 0.60f;
[mapView setRegion:hoboken animated:YES];
Annotation *ann3 = [[Annotation alloc] init];
ann3.title = #"Sushi Lounge";
ann3.subtitle = #"Totawa";
ann3.coordinate = totawa.center;
[mapView addAnnotation:ann3];
}
-(MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
MKPinAnnotationView *MyPin=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"current"];
MyPin.pinColor = MKPinAnnotationColorPurple;
UIButton *advertButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[advertButton addTarget:self action:#selector(button:) forControlEvents:UIControlEventTouchUpInside];
MyPin.rightCalloutAccessoryView = advertButton;
MyPin.draggable = NO;
MyPin.highlighted = YES;
MyPin.animatesDrop=TRUE;
MyPin.canShowCallout = YES;
return MyPin;
}
-(void)button:(id)sender {
NSLog(#"Button action");
}
//Start of Segment control
-(IBAction) changeSegment:(id)sender
{
//streetLabel---------------------------------------------
if(control.selectedSegmentIndex == 0) {
streetLabel.text = #"12 Schuyler Place";
}
if(control.selectedSegmentIndex == 1) {
streetLabel.text = #"200 Hudson St.";
}
if(control.selectedSegmentIndex == 2) {
streetLabel.text = #"235 Route 46 West";
}
//phoneLabel---------------------------------------------
if(control.selectedSegmentIndex == 0) {
phoneLabel.text = #"(973) 539-1135";
}
if(control.selectedSegmentIndex == 1) {
phoneLabel.text = #"(201) 386-1117";
}
if(control.selectedSegmentIndex == 2) {
phoneLabel.text = #"(973) 890-0007";
}
//Monday----------------------------------------------
if(control.selectedSegmentIndex == 0) {
hoursLabel1.text = #"11:30am - 11:00pm";
}
if(control.selectedSegmentIndex == 1) {
hoursLabel1.text = #"11:30pm - 11:30pm";
}
if(control.selectedSegmentIndex == 2) {
hoursLabel1.text = #"11:30am - 10:30pm";
}
//Tuesday------------------------------------------
if(control.selectedSegmentIndex == 0) {
hoursLabel2.text = #"11:30am - 11:00pm";
}
if(control.selectedSegmentIndex == 1) {
hoursLabel2.text = #"11:30am - 11:30pm";
}
if(control.selectedSegmentIndex == 2) {
hoursLabel2.text = #"11:30am - 10:30pm";
}
//Wednesday------------------------------------------
if(control.selectedSegmentIndex == 0) {
hoursLabel3.text = #"11:30am - 11:30pm";
}
if(control.selectedSegmentIndex == 1) {
hoursLabel3.text = #"11:30am - 11:30pm";
}
if(control.selectedSegmentIndex == 2) {
hoursLabel3.text = #"11:30am - 12:00am";
}
//Thursday------------------------------------------
if(control.selectedSegmentIndex == 0) {
hoursLabel4.text = #"11:30am - 12:00am";
}
if(control.selectedSegmentIndex == 1) {
hoursLabel4.text = #"11:30am - 12:00pm";
}
if(control.selectedSegmentIndex == 2) {
hoursLabel4.text = #"11:30am - 11:30pm";
}
//Friday------------------------------------------
if(control.selectedSegmentIndex == 0) {
hoursLabel5.text = #"11:30am - 12:00pm";
}
if(control.selectedSegmentIndex == 1) {
hoursLabel5.text = #"11:30am - 1:00am";
}
if(control.selectedSegmentIndex == 2) {
hoursLabel5.text = #"11:30am - 12:00am";
}
//Saturday------------------------------------------
if(control.selectedSegmentIndex == 0) {
hoursLabel6.text = #"12:00pm - 12:00am";
}
if(control.selectedSegmentIndex == 1) {
hoursLabel6.text = #"12:00pm - 1:00am";
}
if(control.selectedSegmentIndex == 2) {
hoursLabel6.text = #"12:00pm - 12:00am";
}
//Sunday------------------------------------------
if(control.selectedSegmentIndex == 0) {
hoursLabel7.text = #"12:00pm - 11:00pm";
}
if(control.selectedSegmentIndex == 1) {
hoursLabel7.text = #"12:00pm - 11:30pm";
}
if(control.selectedSegmentIndex == 2) {
hoursLabel7.text = #"12:00pm - 10:30pm";
}
if (control.selectedSegmentIndex == 0) {
mapView.center.x == 40.738496;
}
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
*/
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end

better just do more reading, here is a sample code you might want to study:
MapCallouts

One simple solution is to make the annotation variables ann1, ann2, and ann3 ivars instead of local variables in viewDidLoad.
You will then be able to easily access them and change the map's coordinates in the changeSegment: method:
if (control.selectedSegmentIndex == 0) {
//set streetLabel, phoneLabel, and hoursLabelX here also
[mapView setRegion:MKCoordinateRegionMakeWithDistance(ann1.coordinate, 1000, 1000) animated:YES];
}
else
if (control.selectedSegmentIndex == 1) {
//set streetLabel, phoneLabel, and hoursLabelX here also
[mapView setRegion:MKCoordinateRegionMakeWithDistance(ann2.coordinate, 1000, 1000) animated:YES];
}
else
if (control.selectedSegmentIndex == 2) {
//set streetLabel, phoneLabel, and hoursLabelX here also
[mapView setRegion:MKCoordinateRegionMakeWithDistance(ann3.coordinate, 1000, 1000) animated:YES];
}
By the way, you can greatly simplify and shorten the code in changeSegment: by putting all the statements that apply to the same condition together as mentioned in the comments above instead of separately.

Related

How to increase the size and height of view by dragging the view from the corners in UITapGestureRecognizer in iphone?

I am doing the project in which I have to show one Image, when I click on the image one "white view "will come on the upper side of the image. And when I double click on the "two pins" will come out on the "white view". When I pull these two pins the width and height of the white view increase and decrease.
I am not able to do this.
Any Idea from experts would be highly welcome.
Second_View.h file
#import <UIKit/UIKit.h>
#interface Second_View : UIViewController<UIGestureRecognizerDelegate>{
UITapGestureRecognizer *tap;
UISwipeGestureRecognizer *swipe;
UIPanGestureRecognizer *pan;
CGPoint startLocation;
CGFloat lastScale;
CGFloat firstX;
CGFloat firstY;
CGPoint lastLocation;
UIImageView *imageVw;
}
#property (nonatomic) CGPoint center;
#property (nonatomic) NSInteger count;
#property(nonatomic,retain) UIImageView *imageVw;
#end
Second_View.m file
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor grayColor];
imageVw = [[UIImageView alloc]initWithFrame:CGRectMake(200, 200, 500, 400)];
imageVw.image = [UIImage imageNamed:#"redacted2.jpg"];
imageVw.userInteractionEnabled=YES;
imageVw.autoresizesSubviews = YES;
imageVw.alpha = 0.93; // for opacity
[self.view addSubview:imageVw];
tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleTap:)];
tap.numberOfTapsRequired = 1;
[imageVw addGestureRecognizer:tap];
tap.delegate=self;
pan=[[UIPanGestureRecognizer alloc]initWithTarget:self action:#selector(panAction:)];
[pan setMinimumNumberOfTouches:1];
[pan setMaximumNumberOfTouches:2];
[pan setDelegate:self];
count=0;
[imageVw addGestureRecognizer:pan];
}
- (void)panAction:(UIPanGestureRecognizer *)gestureRecognizer {
CGPoint translatedPoint = [(UIPanGestureRecognizer*)gestureRecognizer translationInView:self.view];
if ([(UIPanGestureRecognizer*)gestureRecognizer state] == UIGestureRecognizerStateBegan) {
firstX = [[gestureRecognizer view] center].x;
firstY = [[gestureRecognizer view] center].y;
}
translatedPoint = CGPointMake(firstX+translatedPoint.x, firstY+translatedPoint.y);
[[gestureRecognizer view] setCenter:translatedPoint];
if ([(UIPanGestureRecognizer*)gestureRecognizer state] == UIGestureRecognizerStateEnded) {
CGFloat velocityX = (0.2*[(UIPanGestureRecognizer*)gestureRecognizer velocityInView:self.view].x);
CGFloat finalX = translatedPoint.x + velocityX;
CGFloat finalY = firstY;// 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;
}
}
}
}
-(void)handleTap:(UIPanGestureRecognizer *)gestureRecognizer
{
CGPoint location = [gestureRecognizer locationInView:gestureRecognizer.view];
NSLog(#"x:%f y:%f",location.x,location.y);
NSArray *subViewsOfImage = [imageVw subviews];
for (id subView in subViewsOfImage) {
CGRect frame1=[subView frame];
int x=0;
int y=0;
x=frame1.origin.x+frame1.size.width;
y=frame1.origin.y+frame1.size.height;
if ((location.x>=frame1.origin.x && location.x<x) && (location.y>=frame1.origin.y && location.y<y) )
{
NSLog(#"No");
return;
}
}
derivedView *view=[[derivedView alloc]initWithFrame:CGRectMake(location.x, location.y, 100, 30)];
[view setBackgroundColor:[UIColor whiteColor]];
[imageVw addSubview: view];
NSArray * subViewsOfImage1 = [imageVw subviews];
NSLog(#"subViewsOfImage = %#",subViewsOfImage1);
NSLog(#"Yes");
}
derivedView.h file
#import <UIKit/UIKit.h>
#interface derivedView : UIView<UIGestureRecognizerDelegate>
{
UIPanGestureRecognizer *pan;
UITapGestureRecognizer *tap1;
UITapGestureRecognizer *tap2;
UITapGestureRecognizer *tap3;
CGPoint lastLocation;
CGFloat firstX;
CGFloat firstY;
UIImageView *rPinImgView;
UIImageView *lPinImgView;
}
#end
derivedView.m file
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
pan=[[UIPanGestureRecognizer alloc]initWithTarget:self action:#selector(panAction:)];
[pan setDelegate:self];
[self addGestureRecognizer:pan];
tap1=[[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(tapAction:)];
[tap1 setDelegate:self];
[self addGestureRecognizer:tap1];
}
return self;
}
- (void)tapAction:(UITapGestureRecognizer *)gestureRecognizer {
// lPinImgView=[[UIImageView alloc]initWithFrame:CGRectMake(-15,-20, 30, 30)];
// lPinImgView.image=[UIImage imageNamed:#"pin"];
// // pin.frame=CGRectMake(frame1.origin.x, frame1.origin.y-15, 10, 10);
//
// rPinImgView=[[UIImageView alloc]initWithFrame:CGRectMake (self.frame.size.width-15 ,23, 30, 30)];
// //pin1.frame=CGRectMake(frame1.origin.x+frame1.size.width, frame1.origin.y+5, 10, 10);
// rPinImgView.image=[UIImage imageNamed:#"pin1"];
// [self addSubview:lPinImgView];
// [self addSubview:rPinImgView];
NSArray *subViews=[self subviews];
NSLog(#"subViews%#",subViews);
if ([subViews count]>0) {
[lPinImgView removeFromSuperview];
[rPinImgView removeFromSuperview];
}else
{
lPinImgView=[[UIImageView alloc]initWithFrame:CGRectMake(-15,-20, 30, 30)];
lPinImgView.image=[UIImage imageNamed:#"pin"];
// pin.frame=CGRectMake(frame1.origin.x, frame1.origin.y-15, 10, 10);
rPinImgView=[[UIImageView alloc]initWithFrame:CGRectMake(self.frame.size.width-15 ,23, 30, 30)];
//pin1.frame=CGRectMake(frame1.origin.x+frame1.size.width, frame1.origin.y+5, 10, 10);
rPinImgView.image=[UIImage imageNamed:#"pin1"];
tap2=[[UITapGestureRecognizer alloc]initWithTarget:self action:#selector (rPinImageTap:)];
[rPinImgView addGestureRecognizer:tap2];
[tap2 setDelegate:self];
tap3=[[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(lPinImageTap:)];
[rPinImgView addGestureRecognizer:tap3];
[tap3 setDelegate:self];
[self addSubview:lPinImgView];
[self addSubview:rPinImgView];
}
- (void)lPinImageTap:(UIPanGestureRecognizer *)gestureRecognizer
{
}
- (void)rPinImageTap:(UIPanGestureRecognizer *)gestureRecognizer
{
}
- (void)panAction:(UIPanGestureRecognizer *)gestureRecognizer {
CGPoint translatedPoint = [(UIPanGestureRecognizer*)gestureRecognizer translationInView:self];
if ([(UIPanGestureRecognizer*)gestureRecognizer state] == UIGestureRecognizerStateBegan) {
firstX = [[gestureRecognizer view] center].x;
firstY = [[gestureRecognizer view] center].y;
}
// translatedPoint = CGPointMake(firstX+translatedPoint.x, firstY);
translatedPoint = CGPointMake(firstX+translatedPoint.x, firstY+translatedPoint.y);
[[gestureRecognizer view] setCenter:translatedPoint];
if ([(UIPanGestureRecognizer*)gestureRecognizer state] == UIGestureRecognizerStateEnded) {
CGFloat velocityX = (0.2*[(UIPanGestureRecognizer*)gestureRecognizer velocityInView:self].x);
CGFloat finalX = translatedPoint.x + velocityX;
CGFloat finalY = firstY;// 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;
}
}
}
}
}
Have a look at this below link and download the project and check:
https://github.com/spoletto/SPUserResizableView

iOS "View Controller"

I try to make a game but I have a "warning" that says: "IVBrickerViewController may not respond to -processCollision.
This is the code:
#import "IVBrickerViewController.h"
#implementation IVBrickerViewController
#synthesize scoreLabel;
#synthesize ball;
#synthesize paddle;
#synthesize livesLabel;
#synthesize messageLabel;
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
-(void) accelerometer:(UIAccelerometer *)accelerometer
didAccelerate:(UIAcceleration *)accel
{
float newX = paddle.center.x + (accel.x *12);
if(newX > 30 && newX <290)
paddle.center = CGPointMake(newX, paddle.center.y);
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if (isPlaying) {
UITouch *touch = [[event allTouches] anyObject];
touchOffset = paddle.center.x -
[touch locationInView:touch.view].x;
} else {
[self startPlaying];
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
if (isPlaying) {
UITouch *touch = [[event allTouches] anyObject];
float distanceMoved =
([touch locationInView:touch.view].x + touchOffset) -
paddle.center.x;
float newX = paddle.center.x + distanceMoved;
if (newX > 30 && newX < 290)
paddle.center = CGPointMake( newX, paddle.center.y );
if (newX > 290)
paddle.center = CGPointMake( 290, paddle.center.y );
if (newX < 30)
paddle.center = CGPointMake( 30, paddle.center.y );
}
}
- (void)viewDidLoad {
[super viewDidLoad];
[self initializeBricks];
[self startPlaying];
}
- (void)initializeBricks
{
brickTypes[0] = #"bricktype1.png";
brickTypes[1] = #"bricktype2.png";
brickTypes[2] = #"bricktype3.png";
brickTypes[3] = #"bricktype4.png";
int count = 0;
for (int y = 0; y < BRICKS_HEIGHT; y++)
{
for (int x = 0; x < BRICKS_WIDTH; x++)
{
UIImage *image = [UIImage imageNamed:
brickTypes[count++ % 4]];
bricks[x][y] = [[[UIImageView alloc] initWithImage:image]
autorelease];
CGRect newFrame = bricks[x][y].frame;
newFrame.origin = CGPointMake(x * 64, (y * 40) + 100);
bricks[x][y].frame = newFrame;
[self.view addSubview:bricks[x][y]];
}
}
}
-(void)startPlaying {
if (!lives) {
lives = 3;
score = 0;
}
UIAccelerometer *theAccel = [UIAccelerometer sharedAccelerometer];
theAccel.updateInterval = 1.0f / 30.0f;
theAccel.delegate = self;
ballMovement = CGPointMake(4, 4);
[self initializeTimer];
scoreLabel.text = [NSString stringWithFormat:#"%05d", score];
livesLabel.text = [NSString stringWithFormat:#"%d", lives];
ball.center = CGPointMake(159, 239);
ballMovement = CGPointMake(4, 4);
// choose whether the ball moves left to right or right or right to left
if (arc4random() % 100 < 50)
ballMovement.x = -ballMovement.x;
messageLabel.hidden = YES;
isPlaying = YES;
[self initializeTimer];
}
-(void)pauseGame {
[theTimer invalidate];
theTimer = nil;
}
-(void)initializeTimer {
if (theTimer == nil) {
float theInterval = 1.0f/30.0f;
//I've renamed animateBall: to gamelogic
theTimer = [NSTimer scheduledTimerWithTimeInterval:theInterval target:self
selector:#selector(gameLogic) userInfo:nil repeats:YES];
}
}
-(void)gameLogic {
ball.center = CGPointMake(ball.center.x+ballMovement.x,
ball.center.y+ballMovement.y);
BOOL paddleCollision = ball.center.y >= paddle.center.y - 16 &&
ball.center.y <= paddle.center.y + 16 &&
ball.center.x > paddle.center.x - 32 &&
ball.center.x < paddle.center.x + 32;
if(paddleCollision) {
ballMovement.y = -ballMovement.y;
BOOL there_are_solid_bricks = NO;
for (int y = 0; y < BRICKS_HEIGHT; y++)
{
for (int x = 0; x < BRICKS_WIDTH; x++)
{
if (1.0 == bricks[x][y].alpha)
{
there_are_solid_bricks = YES;
if ( CGRectIntersectsRect(ball.frame, bricks[x][y].frame) )
{
[***self processCollision:bricks[x][y]];***
}
}
else
{
if (bricks[x][y].alpha > 0)
bricks[x][y].alpha -= 0.1;
}
}
}
if (!there_are_solid_bricks) {
[theTimer invalidate];
isPlaying = NO;
lives = 0;
messageLabel.text = #"You Win!";
messageLabel.hidden = NO;
}
if (ball.center.y >= paddle.center.y - 16 && ballMovement.y < 0) {
ball.center = CGPointMake(ball.center.x, paddle.center.y - 16);
} else if (ball.center.y <= paddle.center.y + 16 && ballMovement.y > 0) {
ball.center = CGPointMake(ball.center.x, paddle.center.y + 16);
} else if (ball.center.x >= paddle.center.x - 32 && ballMovement.x < 0) {
ball.center = CGPointMake(paddle.center.x - 32, ball.center.y);
} else if (ball.center.x <= paddle.center.x + 32 && ballMovement.x > 0) {
ball.center = CGPointMake(paddle.center.x + 32, ball.center.y);
}
}
if(ball.center.x > 300 || ball.center.x < 20)
ballMovement.x = -ballMovement.x;
if (ball.center.y < 32)
ballMovement.y = -ballMovement.y;
if (ball.center.y > 444) {
[self pauseGame];
isPlaying = NO;
lives--;
livesLabel.text = [NSString stringWithFormat:#"%d", lives];
if (!lives) {
messageLabel.text = #"Game Over";
} else {
messageLabel.text = #"Ball Out of Bounds";
}
messageLabel.hidden = NO;
}
if(ball.center.y > 444 || ball.center.y < 40)
ballMovement.y = -ballMovement.y;
}
- (void)processCollision:(UIImageView *)brick
{
score += 10;
scoreLabel.text = [NSString stringWithFormat:#"%d", score];
if (ballMovement.x > 0 && brick.frame.origin.x - ball.center.x <= 4)
ballMovement.x = -ballMovement.x;
else if (ballMovement.x < 0 && ball.center.x - (brick.frame.origin.x +
brick.frame.size.width) <= 4)
ballMovement.x = -ballMovement.x;
if (ballMovement.y > 0 && brick.frame.origin.y - ball.center.y <= 4)
ballMovement.y = -ballMovement.y;
else if (ballMovement.y < 0 && ball.center.y - (brick.frame.origin.y +
brick.frame.size.height) <= 4)
ballMovement.y = -ballMovement.y;
brick.alpha -= 0.1;
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)DidReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[scoreLabel release];
[ball release];
[paddle release];
[livesLabel release];
[messageLabel release];
[super dealloc];
}
#end
I HAVE TWO WARNINGS HERE AT THE #END:
{Incomplete implementation of class 'IVBrickerViewController'}.
{Method definition for'-animateBall:'not found}.
I had changed the .h file from: "-(void)animateBall:(NSTimer *)theTimer;"
to: "-(void)gameLogic:(NSTimer *)theTimer;"
but i get the same warning: "Method definition for'-gameLogic:' not found"
I would like to thank those who have tried to help me.
Make sure that you have
- (void)processCollision:(UIImageView *)brick;
in your IVBrickerViewController.h file.
Problem is in your header file (.h).
There is no correct declaration of processCollision method.
Add it to header file.

Zoom issue with UIImageView

I am trying to get pinch/zoom work but to no luck... please check code attached any help is appreciated.
#import "SlideShowViewController.h"
#import "SomAppDelegate.h"
#import "MainCategory.h"
#import <sqlite3.h>
#import "UIImage+Resizing.h"
NSInteger Val;
NSInteger AIX;
NSInteger AIY;
NSInteger Height;
NSInteger Pre;
NSInteger Valtab;
NSInteger ImageVal;
NSInteger ValScroll;
UIToolbar *tabBar;
UIActivityIndicatorView *activityIndicator;
UIActivityIndicatorView *activityIndicator1;
#class SomAppDelegate;
#class SlideShowViewController;
#interface SlideShowView : UIView<UIScrollViewDelegate>
{
NSArray * mImages;
UIImageView * mLeftImageView;
UIImageView * mCurrentImageView;
UIImageView * mRightImageView;
NSUInteger mCurrentImage;
BOOL mSwiping;
UIImageView * result;
NSString *imageName;
CGFloat mSwipeStart;
UIScrollView *NewView;
NSTimer *timer;
//////////////////////////////////////////////////////for pinch and Zoom//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CGPoint gestureStartPoint;
CGPoint wmsImageViewCenter;
double unitDistance;
double initialDistance;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
#property (nonatomic, retain)UIView *NewView;
- (double)getDistance:(CGPoint)fromPoint toPoint:(CGPoint)otherPoint;
-(id)initWithImages:(NSArray *)inImages;
#end
#interface SlideShowView(PrivateMethods)
-(UIImageView *)newPieceViewWithImageNamed:(NSString *)imageName atPostion:(CGPoint)centerPoint;
- (void)animateFirstTouch:(double)scale;
#end
#pragma mark -
#implementation SlideShowView
#synthesize NewView;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (UIImageView *)createImageView:(NSUInteger)inImageIndex
{
if (inImageIndex >= [mImages count])
{
return nil;
}
UIImage *pigImage1 =[UIImage imageWithContentsOfFile:[mImages objectAtIndex:inImageIndex]];
result=[[UIImageView alloc] initWithImage:pigImage1];
pigImage1=nil;
[pigImage1 release];
result.opaque = YES;
CGRect frameRect = [result frame];
unitDistance = [self getDistance:CGPointMake(0, 0) toPoint:CGPointMake(frameRect.size.width, frameRect.size.height)] / 4.0;
result.userInteractionEnabled =NO;
result.alpha = 1.0;
result.backgroundColor = [UIColor blackColor];
result.contentMode = UIViewContentModeScaleAspectFit;
result.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
return result;
}
-(UIImage*)createImage:(NSUInteger)inImageIndex
{
if (inImageIndex >= [mImages count])
{
return nil;
}
UIImage *pigImage1 =[UIImage imageWithContentsOfFile:[mImages objectAtIndex:inImageIndex]];
return pigImage1;
}
- (id)initWithImages:(NSArray *)inImages
{
initialDistance = 1;
unitDistance = 1;
[self setMultipleTouchEnabled:YES];
self.multipleTouchEnabled = YES;
if (self = [super initWithFrame:CGRectZero])
{
mImages = [inImages retain];
NSUInteger imageCount=[inImages count];
ImageVal=imageCount;
if (imageCount > 0)
{
mCurrentImageView = [self createImageView:0];
[self addSubview:mCurrentImageView];
result=nil;
if (imageCount > 1)
{
mRightImageView = [self createImageView:1];
[self addSubview:mRightImageView];
result=nil;
}
}
self.opaque = YES;
self.backgroundColor = [UIColor blackColor];
self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
}
return self;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)dealloc
{
[mImages release];
[result release];
result.image=nil;
result=nil;
[super dealloc];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)layoutSubviews
{
if (mSwiping)
return;
CGSize contentSize =self.frame.size; //self.frame.size;
mLeftImageView.frame = CGRectMake(-contentSize.width, 0.0f, contentSize.width, contentSize.height);
mCurrentImageView.frame = CGRectMake(0.0f,0.0f, contentSize.width, contentSize.height);
mRightImageView.frame = CGRectMake(contentSize.width, 0.0f, contentSize.width, contentSize.height);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//////////////////////////////////////////// code by pinch and zoom ////////////////////////////////////////////////////////////////
if (mCurrentImageView != nil)
{
if ([touches count] > 1) {
NSArray *touchArray = [touches allObjects];
CGPoint p1 = [[touchArray objectAtIndex:0] locationInView:self];
CGPoint p2 = [[touchArray objectAtIndex:1] locationInView:self];
initialDistance = [self getDistance:p1 toPoint:p2];
}
else
{
UITouch *touch = [touches anyObject];
gestureStartPoint = [touch locationInView:self];
wmsImageViewCenter = mCurrentImageView.center;
}
}
//////////////////////////////////////// code by rajeev ////////////////////////////////////////////////////////////////
if ([touches count] != 1)
return;
mSwipeStart = [[touches anyObject] locationInView:self].x;
mSwiping = YES;
mLeftImageView.hidden = NO;
mCurrentImageView.hidden = NO;
mRightImageView.hidden = NO;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
CGSize contentSize =self.frame.size;
///////////////////////////////////////////////////for pinch and zoom/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (mCurrentImageView != nil)
{
if ([touches count] > 1)
{
NSArray *touchArray = [touches allObjects];
CGPoint p1 = [[touchArray objectAtIndex:0] locationInView:self];
CGPoint p2 = [[touchArray objectAtIndex:1] locationInView:self];
float distanceNew = [self getDistance:p1 toPoint:p2];
float dx = (distanceNew - initialDistance)/unitDistance;
double scale = fabs(mCurrentImageView.transform.a + dx);
[self animateFirstTouch:scale];
initialDistance = distanceNew;
}
else if([touches count]==1)
{
UITouch *touch = [touches anyObject];
CGPoint currentPosition = [touch locationInView:self];
CGFloat deltaX = gestureStartPoint.x - currentPosition.x;
CGFloat deltaY = gestureStartPoint.y - currentPosition.y;
mCurrentImageView.center = CGPointMake(wmsImageViewCenter.x - deltaX, wmsImageViewCenter.y - deltaY);
mCurrentImageView.opaque = YES;
mCurrentImageView.contentMode = UIViewContentModeScaleAspectFit;
mCurrentImageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
}
}
//////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CGRect frameRect = [mCurrentImageView frame];
if(frameRect.size.height>Height)
{
contentSize.width=frameRect.size.width;
contentSize.height= frameRect.size.height;
mLeftImageView.frame = CGRectMake(-contentSize.width, 0.0f, contentSize.width, contentSize.height);
mRightImageView.frame = CGRectMake(contentSize.width, 0.0f, contentSize.width, contentSize.height);
}
else
{
if (! mSwiping || [touches count] != 1)
return;
CGFloat swipeDistance = [[touches anyObject] locationInView:self].x - mSwipeStart;
mLeftImageView.frame = CGRectMake(swipeDistance - contentSize.width, 0.0f, contentSize.width, contentSize.height);
mCurrentImageView.frame = CGRectMake(swipeDistance,0.0f, contentSize.width, contentSize.height);
mRightImageView.frame = CGRectMake(swipeDistance + contentSize.width, 0.0f, contentSize.width, contentSize.height);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if (! mSwiping)
return;
CGSize contentSize = self.frame.size;
NSUInteger count = [mImages count];
CGFloat swipeDistance = [[touches anyObject] locationInView:self].x - mSwipeStart;
CGRect frameRect = [mCurrentImageView frame];
if(frameRect.size.height>Height)
{
if (mCurrentImage > 0 && swipeDistance > 250.0f)
{
[mRightImageView removeFromSuperview];
mRightImageView.image=nil;
mRightImageView=nil;
result.image=nil;
result=nil;
mRightImageView = mCurrentImageView;
mCurrentImageView = mLeftImageView;
mCurrentImage--;
if (mCurrentImage > 0)
{
mLeftImageView = [self createImageView:mCurrentImage - 1];
mLeftImageView.hidden = YES;
[self addSubview:mLeftImageView];
result=nil;
}
else
{
mLeftImageView = nil;
result=nil;
}
[UIView beginAnimations:#"swipe" context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[UIView setAnimationDuration:0.3f];
CGSize contentSize = self.frame.size;
mLeftImageView.frame = CGRectMake(-contentSize.width, 0.0f, contentSize.width, contentSize.height);
mCurrentImageView.frame = CGRectMake(0.0f,0.0f, contentSize.width, contentSize.height);
mRightImageView.frame = CGRectMake(contentSize.width, 0.0f, contentSize.width, contentSize.height);
[UIView commitAnimations];
mSwiping = NO;
}
//////////////////////////////////////////////////////////right Swaping ///////////////////////////////////////////////////////////////////////
else if (mCurrentImage < count - 1 && swipeDistance < -250.0f)
{
[mLeftImageView removeFromSuperview];
mLeftImageView.image=nil;
mLeftImageView=nil;
result.image=nil;
result=nil;
mLeftImageView = mCurrentImageView;
mCurrentImageView = mRightImageView;
mCurrentImage++;
if (mCurrentImage < count - 1)
{
mRightImageView = [self createImageView:mCurrentImage + 1];
mRightImageView.hidden = YES;
[self addSubview:mRightImageView];
result=nil;
}
else
{
mRightImageView=nil;
result=nil;
}
[UIView beginAnimations:#"swipe" context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[UIView setAnimationDuration:0.3f];
CGSize contentSize = self.frame.size;
mLeftImageView.frame = CGRectMake(-contentSize.width, 0.0f, contentSize.width, contentSize.height);
mCurrentImageView.frame = CGRectMake(0.0f,0.0f, contentSize.width, contentSize.height);
mRightImageView.frame = CGRectMake(contentSize.width, 0.0f, contentSize.width, contentSize.height);
[UIView commitAnimations];
mSwiping = NO;
}
}
else
{
///////////////////////////////////////////////////// Left swaping////////////////////////////////////////////////////////////////////////////
if (mCurrentImage > 0 && swipeDistance > 50.0f)
{
[mRightImageView removeFromSuperview];
mRightImageView.image=nil;
mRightImageView=nil;
result.image=nil;
result=nil;
mRightImageView = mCurrentImageView;
mCurrentImageView = mLeftImageView;
mCurrentImage--;
if (mCurrentImage > 0)
{
mLeftImageView = [self createImageView:mCurrentImage - 1];
mLeftImageView.hidden = YES;
[self addSubview:mLeftImageView];
result=nil;
}
else
{
mLeftImageView = nil;
result=nil;
}
}
//////////////////////////////////////////////////////////right Swaping ///////////////////////////////////////////////////////////////////////
else if (mCurrentImage < count - 1 && swipeDistance < -50.0f)
{
[mLeftImageView removeFromSuperview];
mLeftImageView.image=nil;
mLeftImageView=nil;
result.image=nil;
result=nil;
mLeftImageView = mCurrentImageView;
mCurrentImageView = mRightImageView;
mCurrentImage++;
if (mCurrentImage < count - 1)
{
mRightImageView = [self createImageView:mCurrentImage + 1];
mRightImageView.hidden = YES;
[self addSubview:mRightImageView];
result=nil;
}
else
{
mRightImageView=nil;
result=nil;
}
}
[UIView beginAnimations:#"swipe" context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[UIView setAnimationDuration:0.3f];
mLeftImageView.frame = CGRectMake(-contentSize.width, 0.0f, contentSize.width, contentSize.height);
mCurrentImageView.frame = CGRectMake(0.0f,0.0f, contentSize.width, contentSize.height);
mRightImageView.frame = CGRectMake(contentSize.width, 0.0f, contentSize.width, contentSize.height);
[UIView commitAnimations];
mSwiping = NO;
}
}
///////////////////////////////////////////////////////////////////////////////////Tab Bar functionality /////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark === Animating subviews ===
#pragma mark
- (void)animateFirstTouch:(double)scale
{
if (mCurrentImageView != nil)
{
CGAffineTransform transform = CGAffineTransformMakeScale(scale, scale);
mCurrentImageView.transform = transform;
/*
CGSize contentSize = self.frame.size;
if(contentSize.width>1024)
{
//contentSize= CGSizeMake(1024, 1024);
mCurrentImageView.opaque = YES;
mCurrentImageView.contentMode = UIViewContentModeScaleAspectFit;
mCurrentImageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
mCurrentImageView.clipsToBounds = YES;
//mCurrentImageView.frame = self.bounds;
[mCurrentImageView setNeedsLayout];
}
*/
}
}
- (double)getDistance:(CGPoint)fromPoint toPoint:(CGPoint)otherPoint
{
double deltaX = otherPoint.x - fromPoint.x;
double deltaY = otherPoint.y - fromPoint.y;
return sqrt(pow(deltaX, 2) + pow(deltaY, 2));
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// SlideShowView
#implementation SlideShowViewController
#synthesize Values,PreVal;
#synthesize ImageID,ImagePath,ImagePos,CatID,SlideID,CID;
/*
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
int counter=0;
ImageID=[[NSMutableArray alloc]init];
ImagePath=[[NSMutableArray alloc]init];
ImagePos=[[NSMutableArray alloc] init];
CatID=[[NSMutableArray alloc] init];
SlideID=[[NSMutableArray alloc] init];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:#"Category.sqlite3"];
sqlite3 *db;
if (sqlite3_open([writablePath UTF8String], &db) == SQLITE_OK)
{
sqlite3_stmt *statement = nil;
NSString *insertQuery=[NSString stringWithFormat:#"select *from Image where SlideID=%d and CatID=%d;",Values,CID];
const char *sql = [insertQuery cStringUsingEncoding:NSASCIIStringEncoding];
if(sqlite3_prepare_v2(db, sql, -1, &statement, NULL) != SQLITE_OK)
{
NSAssert1(0,#"error1",sqlite3_errmsg(db));
}
else
{
while(sqlite3_step(statement) == SQLITE_ROW)
{
counter++;
[ImageID addObject:[NSString stringWithFormat:#"%s",(char *)sqlite3_column_text(statement,0)]];
[ImagePath addObject:[NSString stringWithFormat:#"%s",(char *)sqlite3_column_text(statement,1)]];
[ImagePos addObject:[NSString stringWithFormat:#"%s",(char *)sqlite3_column_text(statement,2)]];
[CatID addObject:[NSString stringWithFormat:#"%s",(char *)sqlite3_column_text(statement,3)]];
[SlideID addObject:[NSString stringWithFormat:#"%s",(char *)sqlite3_column_text(statement,4)]];
}
sqlite3_finalize(statement);
}
}
sqlite3_close(db);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Slide= [[[SlideShowView alloc] initWithImages:ImagePath] autorelease];
self.view=Slide;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
tabBar.alpha = 0.0;
if (interfaceOrientation == UIInterfaceOrientationLandscapeLeft)
{ AIX=510;
AIY=360;
Valtab=690;
ValScroll=730.0;
Height=1008;
}
else if(interfaceOrientation == UIInterfaceOrientationLandscapeRight)
{
AIX=510;
AIY=360;
Valtab=690;
ValScroll=730.0;
Height=750;
}
else if(interfaceOrientation == UIInterfaceOrientationPortrait)
{
AIX=360;
AIY=510;
Valtab=945;
ValScroll=530;
Height=1008;
}
else
{
AIX=360;
AIY=510;
Valtab=945;
ValScroll=530.0;
Height=750;
}
return YES; //(interfaceOrientation == UIInterfaceOrientationLandscapeLeft);
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (void)dealloc {
[super dealloc];
[activityIndicator release];
}
#end
Try rearranging your init method a little:
- (id)initWithImages:(NSArray *)inImages
{
initialDistance = 1;
unitDistance = 1;
// remove these
// [self setMultipleTouchEnabled:YES];
// self.multipleTouchEnabled = YES;
if (self = [super initWithFrame:CGRectZero])
{
mImages = [inImages retain];
NSUInteger imageCount=[inImages count];
ImageVal=imageCount;
if (imageCount > 0)
{
mCurrentImageView = [self createImageView:0];
[self addSubview:mCurrentImageView];
result=nil;
if (imageCount > 1)
{
mRightImageView = [self createImageView:1];
[self addSubview:mRightImageView];
result=nil;
}
}
self.opaque = YES;
self.backgroundColor = [UIColor blackColor];
self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
// move to here after the init on super is done
self.multipleTouchEnabled = YES;
}
return self;
}
Calling init on the super probably undoes your efforts to set it beforehand.

How can i provide Zoomin-Zoomout,Paging functionality in to UIScrollView?

I have an array of Image URl's from that array i have displayed my Images in Scrollview because i want to take the advantage of Paging and zooming so what should i do to achieve this task?suppose my array contains 10 URL then by each time scrolling i should get different image and i could also performing Zooming-In and Zooming-Out any of the 10 Images so please give me some guidelines to achieve my task.Thanks in Advance.
Try this
- (void)setCurrentPage:(NSUInteger)page {
if (page == offsetX)
return;
offsetX = page;
// in a real app, this would be a good place to instantiate more view controllers -- see SDK examples
}
- (CGSize)pageSize {
CGSize pageSize = scrollView1.frame.size;
if (UIInterfaceOrientationIsLandscape(self.interfaceOrientation))
return CGSizeMake(pageSize.height, pageSize.width);
else
return pageSize;
}
- (void)setPagingMode {
// reposition pages side by side, add them back to the view
CGSize pageSize = [self pageSize];
NSUInteger page = 0;
for (UIView *view in imgViewArray) {
if (!view.superview)
[scrollView1 addSubview:view];
view.frame = CGRectMake(pageSize.width * page++, 0, pageSize.width, pageSize.height);
}
scrollView1.pagingEnabled = YES;
scrollView1.showsVerticalScrollIndicator = scrollView1.showsHorizontalScrollIndicator = NO;
scrollView1.contentSize = CGSizeMake(pageSize.width * [imgViewArray count], pageSize.height);
scrollView1.contentOffset = CGPointMake(pageSize.width * offsetX, 0);
scrollViewMode = ScrollViewModePaging;
}
- (void)setZoomingMode {
NSLog(#"setZoomingMode");
scrollViewMode = ScrollViewModeZooming; // has to be set early, or else currentPage will be mistakenly reset by scrollViewDidScroll
// hide all pages except the current one
NSUInteger page = 0;
for (UIView *view in imgViewArray)
if (offsetX != page++)
[view removeFromSuperview];
scrollView1.pagingEnabled = NO;
scrollView1.showsVerticalScrollIndicator = scrollView1.showsHorizontalScrollIndicator = YES;
pendingOffsetDelta = scrollView1.contentOffset.x;
scrollView1.bouncesZoom = YES;
}
- (void)scrollViewDidScroll:(UIScrollView *)aScrollView
{
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
// offsetX=(aScrollView.contentOffset.x)/768;
//NSLog(#"Page No:%d",offsetX);
if (scrollViewMode == ScrollViewModePaging)
[self setCurrentPage:roundf(scrollView1.contentOffset.x / [self pageSize].width)];
}
else
{
//offsetX=(aScrollView.contentOffset.x)/320;
//NSLog(#"Page No:%d",offsetX);
if (scrollViewMode == ScrollViewModePaging)
[self setCurrentPage:roundf(scrollView1.contentOffset.x / [self pageSize].width)];
}
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)aScrollView
{
NSLog(#"viewForZoomingInScrollView");
if (scrollViewMode != ScrollViewModeZooming)
[self setZoomingMode];
return [imgViewArray objectAtIndex:offsetX];
}
- (void)scrollViewDidEndZooming:(UIScrollView *)aScrollView withView:(UIView *)view atScale:(float)scale {
NSLog(#"scrollViewDidEndZooming");
if (scrollView1.zoomScale == scrollView1.minimumZoomScale)
[self setPagingMode];
else if (pendingOffsetDelta > 0) {
UIView *view = [imgViewArray objectAtIndex:offsetX];
view.center = CGPointMake(view.center.x - pendingOffsetDelta, view.center.y);
CGSize pageSize = [self pageSize];
scrollView1.contentOffset = CGPointMake(scrollView1.contentOffset.x - pendingOffsetDelta, scrollView1.contentOffset.y);
scrollView1.contentSize = CGSizeMake(pageSize.width * scrollView1.zoomScale, pageSize.height * scrollView1.zoomScale);
pendingOffsetDelta = 0;
}
}

MapKit: How can I pan and zoom to fit all my annotations?

So I've got a bunch of annotations spread out on my map... everything is just dandy. Now I need to be able to set the map's position and zoom so they all fit perfectly. How can I do this?
From Apple forums...
- (void)recenterMap {
NSArray *coordinates = [self.mapView valueForKeyPath:#"annotations.coordinate"];
CLLocationCoordinate2D maxCoord = {-90.0f, -180.0f};
CLLocationCoordinate2D minCoord = {90.0f, 180.0f};
for(NSValue *value in coordinates) {
CLLocationCoordinate2D coord = {0.0f, 0.0f};
[value getValue:&coord];
if(coord.longitude > maxCoord.longitude) {
maxCoord.longitude = coord.longitude;
}
if(coord.latitude > maxCoord.latitude) {
maxCoord.latitude = coord.latitude;
}
if(coord.longitude < minCoord.longitude) {
minCoord.longitude = coord.longitude;
}
if(coord.latitude < minCoord.latitude) {
minCoord.latitude = coord.latitude;
}
}
MKCoordinateRegion region = {{0.0f, 0.0f}, {0.0f, 0.0f}};
region.center.longitude = (minCoord.longitude + maxCoord.longitude) / 2.0;
region.center.latitude = (minCoord.latitude + maxCoord.latitude) / 2.0;
region.span.longitudeDelta = maxCoord.longitude - minCoord.longitude;
region.span.latitudeDelta = maxCoord.latitude - minCoord.latitude;
[self.mapView setRegion:region animated:YES];
}
#interface MKMapView (zoomToFit)
- (void)zoomToFitOverlays; //Animation defaults to YES
- (void)zoomToFitOverlay:(id<MKOverlay>)anOverlay;
- (void)zoomToFitOverlays:(NSArray *)someOverlays;
- (void)zoomToFitOverlaysAnimated:(BOOL)animated;
- (void)zoomToFitOverlay:(id<MKOverlay>)anOverlay animated:(BOOL)animated;
- (void)zoomToFitOverlays:(NSArray *)someOverlays animated:(BOOL)animated;
- (void)zoomToFitOverlays:(NSArray *)someOverlays animated:(BOOL)animated insetProportion:(CGFloat)insetProportion; //inset 0->1, defaults in other methods to .1 (10%)
#end
#implementation MKMapView (zoomToFit)
#pragma mark -
#pragma mark Zoom to Fit
- (void)zoomToFitOverlays {
[self zoomToFitOverlaysAnimated:YES];
}
- (void)zoomToFitOverlay:(id<MKOverlay>)anOverlay {
[self zoomToFitOverlay:[NSArray arrayWithObject:anOverlay] animated:YES];
}
- (void)zoomToFitOverlays:(NSArray *)someOverlays {
[self zoomToFitOverlays:someOverlays animated:YES];
}
- (void)zoomToFitOverlaysAnimated:(BOOL)animated {
[self zoomToFitOverlays:self.overlays animated:animated];
}
- (void)zoomToFitOverlay:(id<MKOverlay>)anOverlay animated:(BOOL)animated {
[self zoomToFitOverlays:[NSArray arrayWithObject:anOverlay] animated:YES];
}
- (void)zoomToFitOverlays:(NSArray *)someOverlays animated:(BOOL)animated {
[self zoomToFitOverlays:someOverlays animated:animated insetProportion:.1];
}
- (void)zoomToFitOverlays:(NSArray *)someOverlays animated:(BOOL)animated insetProportion:(CGFloat)insetProportion {
//Check
if ( !someOverlays || !someOverlays.count ) {
return;
}
//Union
MKMapRect mapRect = MKMapRectNull;
if ( someOverlays.count == 1 ) {
mapRect = ((id<MKOverlay>)someOverlays.lastObject).boundingMapRect;
} else {
for ( id<MKOverlay> anOverlay in someOverlays ) {
mapRect = MKMapRectUnion(mapRect, anOverlay.boundingMapRect);
}
}
//Inset
CGFloat inset = (CGFloat)(mapRect.size.width*insetProportion);
mapRect = [self mapRectThatFits:MKMapRectInset(mapRect, inset, inset)];
//Set
MKCoordinateRegion region = MKCoordinateRegionForMapRect(mapRect);
[self setRegion:region animated:animated];
}
#end