problem with uiimageView collision detection - iphone

here is my code:
-(void)moveTheImage
{
for (NSUInteger i = 0; i < [views count]; i++)
{
imageView = [views objectAtIndex:i];
X = [[XArray objectAtIndex:i] floatValue];
Y = [[YArray objectAtIndex:i] floatValue];
imageView.center=CGPointMake(imageView.center.x + X, imageView.center.y + Y);
}
if(!intersectFlag)
{
if(CGRectIntersectsRect(imageView.frame,centre.frame))
{
imageView.alpha=0.5;
intersectFlag = YES;
++count;
}
}
else
{
if(!CGRectIntersectsRect(imageView.frame,centre.frame))
{
intersectFlag = NO;
}
}
}
My problem is that "imageView.alpha=0.5" doesn't work.I don't know why ?

Related

UIApplicationWillEnterForegroundNotification not called

Hi I am very new in Iphone Development. I have a question :
I am using UIApplicationDeligate in my Appdeligate class and in this class i use two methods
applicationDidEnterBackground and applicationdisEnterForeGround. then these method works fine , when my app goes in background or in comes in foreground then flow goes inside these method.
But in another UiViewController class i attach listener for UIApplicationdidEnterForegroundNotification and UiApplicationdidEnterBackgroundNotification.
now when my app goes in background then flow goes in background method but when my app comes in foreground then app flow never comes in foreground method.
code which i am using in AppDelegate Class :
- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:timertimetobefired forKey:#"TimerTimeToFired"];
[defaults setValue:timerrecipename forKey:#"TimerRecipeName"];
[defaults setObject:storingbuttonstate forKey:#"TimerButtonState"];
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
timertimetobefired = [defaults objectForKey:#"TimerTimeToFired"];
timerrecipename = [defaults objectForKey:#"TimerRecipeName"];
storingbuttonstate = [defaults objectForKey:#"TimerButtonState"];
}
and code which i am using inside UiViewController class :
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(goBackground)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
[[NSNotificationCenter defaultCenter]
addObserver:#"forground"
selector:#selector(doMyLayoutStuff:)
name: UIApplicationWillEnterForegroundNotification
object:nil];
- (void) goBackground
{
if(timer != nil && [timer isValid])
{
[timer invalidate], timer = nil;
}
}
can anyone tell me what wrong with this code . Thanks in advance.
code inside doMylayoutStuff :
- (void)doMyLayoutStuff:(id)sender
{
fortimer=0;
appdelegate.imgRecipePhoto=nil;
recipeMakingTime=0;
arrForStepsReminder=[[NSMutableArray alloc]init];
[arrForStepsReminder removeAllObjects];
arrForSteps5=[[NSMutableArray alloc]init];
[arrForSteps5 removeAllObjects];
arrForButtonSelection=[[NSMutableArray alloc]init];
[arrForButtonSelection removeAllObjects];
[arrForSteps5 addObjectsFromArray:appdelegate.arrStepsandTime];
arrayforshowingdata = [[NSMutableArray alloc]initWithCapacity:arrForSteps5.count];
for (int i=0; i<[arrForSteps5 count]; i++)
{
//nitin tyagi. 6/08/2013.
// NSString *str12=[[arrForSteps5 objectAtIndex:i]objectForKey:#"RecipestepTime"];
// if (str12.length==0)
// {
// [arrForSteps5 removeObjectAtIndex:i];
// }
// else
// {
// }
NSString *timer1 = [[arrForSteps5 objectAtIndex:i]objectForKey:#"RecipeTimer1"];
NSString *timer2 = [[arrForSteps5 objectAtIndex:i]objectForKey:#"RecipeTimer2"];
NSString *timer3 = [[arrForSteps5 objectAtIndex:i]objectForKey:#"RecipeTimer3"];
NSString *timer4 = [[arrForSteps5 objectAtIndex:i]objectForKey:#"RecipeTimer4"];
timer1 = [timer1 stringByReplacingOccurrencesOfString:#" " withString:#""];
timer2 = [timer2 stringByReplacingOccurrencesOfString:#" " withString:#""];
timer3 = [timer3 stringByReplacingOccurrencesOfString:#" " withString:#""];
timer4 = [timer4 stringByReplacingOccurrencesOfString:#" " withString:#""];
NSMutableArray *finaltimerarray = [[NSMutableArray alloc]init];
int totalminute = 0;
int hours = 0;
if(([timer1 hasSuffix:#"mins"] || [timer1 hasSuffix:#"minute"] || [timer1 hasSuffix:#"min"]) || ([timer1 isEqualToString:#"0"]))
{
if(![timer1 isEqualToString:#"0"]){
NSRange range = [timer1 rangeOfString:#"min"];
NSString *minutes = [timer1 substringToIndex:range.location];
totalminute = totalminute + [minutes intValue];
NSNumber* xWrapped = [NSNumber numberWithInt:[minutes intValue]];
[finaltimerarray addObject:xWrapped];
}
else
{
[finaltimerarray addObject:[NSNumber numberWithInt:0]];
}
// NSLog(#"totalminute minute is = %#",totalminute);
}
else if(([timer1 hasSuffix:#"hours"] || [timer1 hasSuffix:#"hrs"] || [timer1 hasSuffix:#"hour"] || [timer1 hasSuffix:#"hr"]) )
{
if(![timer1 isEqualToString:#"0"]){
NSRange range = [timer1 rangeOfString:#"h"];
NSString *hours = [timer1 substringToIndex:range.location];
int minute = [hours intValue] * 60;
totalminute = totalminute + minute;
NSNumber* xWrapped = [NSNumber numberWithInt:minute];
[finaltimerarray addObject:xWrapped];
}
else
{
[finaltimerarray addObject:[NSNumber numberWithInt:0]];
}
// NSLog(#"timer1 minute is = %#",minutes);
}
if(([timer2 hasSuffix:#"mins"] || [timer2 hasSuffix:#"minute"] || [timer2 hasSuffix:#"min"]) || ([timer2 isEqualToString:#"0"]))
{
if(![timer2 isEqualToString:#"0"]){
NSRange range = [timer2 rangeOfString:#"min"];
NSString *minutes = [timer2 substringToIndex:range.location];
totalminute = totalminute + [minutes intValue];
NSNumber* xWrapped = [NSNumber numberWithInt:[minutes intValue]];
[finaltimerarray addObject:xWrapped];
}
else
{
[finaltimerarray addObject:[NSNumber numberWithInt:0]];
}
// NSLog(#"timer2 minute is = %#",minutes);
}
else if(([timer2 hasSuffix:#"hours"] || [timer2 hasSuffix:#"hrs"] || [timer2 hasSuffix:#"hour"] || [timer2 hasSuffix:#"hr"]) )
{
if(![timer2 isEqualToString:#"0"])
{
NSRange range = [timer2 rangeOfString:#"h"];
NSString *hours = [timer2 substringToIndex:range.location];
int minute = [hours intValue] * 60;
totalminute = totalminute + minute;
NSNumber* xWrapped = [NSNumber numberWithInt:minute];
[finaltimerarray addObject:xWrapped];
}
else
{
[finaltimerarray addObject:[NSNumber numberWithInt:0]];
}
// NSLog(#"timer1 minute is = %#",minutes);
}
if(([timer3 hasSuffix:#"mins"] || [timer3 hasSuffix:#"minute"] || [timer3 hasSuffix:#"min"]) || ([timer3 isEqualToString:#"0"]))
{
if( ![timer3 isEqualToString:#"0"])
{
NSRange range = [timer3 rangeOfString:#"min"];
NSString *minutes = [timer3 substringToIndex:range.location];
totalminute = totalminute + [minutes intValue];
NSNumber* xWrapped = [NSNumber numberWithInt:[minutes intValue]];
[finaltimerarray addObject:xWrapped];
}
else
{
[finaltimerarray addObject:[NSNumber numberWithInt:0]];
}
// NSLog(#"timer3 minute is = %#",minutes);
}
else if(([timer3 hasSuffix:#"hours"] || [timer3 hasSuffix:#"hrs"] || [timer3 hasSuffix:#"hour"] || [timer3 hasSuffix:#"hr"]) )
{
if(![timer3 isEqualToString:#"0"]){
NSRange range = [timer3 rangeOfString:#"h"];
NSString *hours = [timer3 substringToIndex:range.location];
int minute = [hours intValue] * 60;
totalminute = totalminute + minute;
NSNumber* xWrapped = [NSNumber numberWithInt:minute];
[finaltimerarray addObject:xWrapped];
}
else
{
[finaltimerarray addObject:[NSNumber numberWithInt:0]];
}
// NSLog(#"timer1 minute is = %#",minutes);
}
if(([timer4 hasSuffix:#"mins"] || [timer4 hasSuffix:#"minute"] || [timer4 hasSuffix:#"min"]) || ([timer4 isEqualToString:#"0"]))
{
if(![timer4 isEqualToString:#"0"])
{
NSRange range = [timer4 rangeOfString:#"min"];
NSString *minutes = [timer4 substringToIndex:range.location];
totalminute = totalminute + [minutes intValue];
NSNumber* xWrapped = [NSNumber numberWithInt:[minutes intValue]];
[finaltimerarray addObject:xWrapped];
}
else
{
[finaltimerarray addObject:[NSNumber numberWithInt:0]];
}
// NSLog(#"timer4 minute is = %#",minutes);
}
else if(([timer4 hasSuffix:#"hours"] || [timer4 hasSuffix:#"hrs"] || [timer4 hasSuffix:#"hour"] || [timer4 hasSuffix:#"hr"]) )
{
if(![timer4 isEqualToString:#"0"]){
NSRange range = [timer4 rangeOfString:#"h"];
NSString *hours = [timer4 substringToIndex:range.location];
int minute = [hours intValue] * 60;
totalminute = totalminute + minute;
NSNumber* xWrapped = [NSNumber numberWithInt:minute];
[finaltimerarray addObject:xWrapped];
}
else
{
[finaltimerarray addObject:[NSNumber numberWithInt:0]];
}
// NSLog(#"timer1 minute is = %#",minutes);
}
[arrayforshowingdata addObject:finaltimerarray];
[finaltimerarray release];
}
for (int i=0; i<[arrayforshowingdata count]; i++)
{
NSMutableArray *arraydata = [arrayforshowingdata objectAtIndex:i];
for (int j=0; j<[arraydata count]; j++)
{
[arrForStepsReminder addObject:#"0"];
}
[arrForButtonSelection addObject:#"M"];
}
lblDisplayTimer.text=#"00:00:00";
lblRecipeName.text=appdelegate.strRecipeName;
currentdate = [NSDate date];
NSDate *timetobefired = appdelegate.timertimetobefired;
timerrecipe = appdelegate.timerrecipename;
if(timerrecipe != nil && ([timerrecipe isEqualToString:appdelegate.strRecipeName]) && timetobefired != nil)
{
NSTimeInterval secondsBetween = [timetobefired timeIntervalSinceDate:currentdate];
NSInteger time = round(secondsBetween);
int second = (int)time;
if(second > 0)
{
secondsLeft = second;
arrForButtonSelection = appdelegate.storingbuttonstate;
[btnOnOff setOn:YES];
if(![timer isValid])
{
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(updateCountdown) userInfo:nil repeats:YES];
}
}
else
{
secondsLeft = 0;
}
}
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(goBackground)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(doMyLayoutStuff:)
name: UIApplicationWillEnterForegroundNotification
object:nil];
}
Change the observer to "self" in your addObserver call
i.e
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(doMyLayoutStuff:)
name: UIApplicationWillEnterForegroundNotification
object:nil];

Changing labels after swithiching between views

I have two-views app for iPhone. On first one I call code that does this every second with NSTimer:
update variables
make sound
update label
update image position
When I start app - everything works perfect. When I go to other view and then go back to first screen - 1 and 2 works fine, but 3 and 4 resets and does not work at all.
What could be the problem?
Looks like it loses "hooks" to elements...
-(void)countup {
DeccelFloat += 0.4;
SpeedFloat += 5/(DeccelFloat);
SpeedInt = lroundf(SpeedFloat);
speed.text = [NSString stringWithFormat:#"%i", SpeedInt];
imageview.center = CGPointMake(imageview.center.x, imageview.center.y+3);
if (imageview.center.y < 280) {
imageview.alpha = 1;
if (SpeedFloat > MaxSpeedValue) {
[self playalarm];
}else{
[self playbeep];
}
}
if ((imageview.center.y >= 280) && (imageview.center.y < 283)) {
if (SpeedFloat > MaxSpeedValue) {
[self playshot];
}else{
[self playbeepbeep];
}
}
if ((imageview.center.y >= 280) && (imageview.center.y < 350)) {
imageview.alpha = 0.5-(0.5/70)*(imageview.center.y - 280);
}
if (imageview.center.y >= 350) {
imageview.alpha = 0;
imageview.center = CGPointMake(imageview.center.x, 180);
}
}
And here is my timer:
- (void)viewDidLoad
{
[super viewDidLoad];
MaxSpeedValue = 60;
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSNumber *maxspeedsetttings = nil;
NSNumber *blinkingsetttings = nil;
NSNumber *startedsetttings = nil;
if (standardUserDefaults) {
maxspeedsetttings = [standardUserDefaults objectForKey:#"maxspeedsetttings"];
blinkingsetttings = [standardUserDefaults objectForKey:#"blinkingsetttings"];
startedsetttings = [standardUserDefaults objectForKey:#"startedsetttings"];
}
MaxSpeedDef = [maxspeedsetttings intValue];
if (MaxSpeedDef == 1) {
maxspeed.text = [NSString stringWithFormat:#"%i", MaxSpeedValue];
}else{
maxspeed.alpha = 0;
maxspeedlabel.alpha = 0;
}
imageview.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:#"0.png"],
[UIImage imageNamed:#"5.png"],
[UIImage imageNamed:#"10.png"],
nil];
imageview.animationDuration = 1;
imageview.animationRepeatCount = 0;
BlinkingDef = [blinkingsetttings intValue];
if (BlinkingDef == 1) {
[imageview startAnimating];
}else{
[imageview stopAnimating];
}
[self.view addSubview:imageview];
StartedDef = [startedsetttings intValue];
if (StartedDef == 0) {
SpeedFloat = 0;
DeccelFloat = 0;
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(countup) userInfo:nil repeats:YES];
StartedDef = 1;
if (standardUserDefaults) {
[standardUserDefaults setObject:[NSNumber numberWithInt:StartedDef] forKey:#"startedsetttings"];
[standardUserDefaults synchronize];
}
}
}

Getting CorePlot bar chart to display float values instead of integers?

Basically, I have this class which I am using to display data in a CorePlot bar chart:
#import "BarChartViewController.h"
#import "AppDelegate.h"
#import "Project.h"
#import "Currency.h"
#import "TotalValueCalculator.h"
#define BAR_POSITION #"POSITION"
#define BAR_HEIGHT #"HEIGHT"
#define COLOR #"COLOR"
#define CATEGORY #"CATEGORY"
#define AXIS_START 0
#interface BarChartViewController ()
#end
#implementation BarChartViewController
{
int count;
}
#synthesize data;
#synthesize graph;
#synthesize hostingView;
#synthesize graphType;
//Finds the maximum value from an array of ints
int findMax (int numbers[], int N){
int max = numbers[0];
for (int i = 0; i < N; i++)
if(max<numbers[i]) max = numbers[i];
return max;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void) generateBarPlot
{
//Create host view
self.hostingView = [[CPTGraphHostingView alloc]
initWithFrame:[[UIScreen mainScreen]bounds]];
[self.view addSubview:self.hostingView];
//Create graph and set it as host view's graph
self.graph = [[CPTXYGraph alloc] initWithFrame:self.hostingView.bounds];
[self.hostingView setHostedGraph:self.graph];
//set graph padding and theme
self.graph.plotAreaFrame.paddingTop = 20.0f;
self.graph.plotAreaFrame.paddingRight = 20.0f;
self.graph.plotAreaFrame.paddingBottom = 170.0f;
self.graph.plotAreaFrame.paddingLeft = 70.0f;
[self.graph applyTheme:[CPTTheme themeNamed:kCPTDarkGradientTheme]];
//set axes ranges
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(AXIS_START) length:CPTDecimalFromFloat(50)];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:
CPTDecimalFromFloat(AXIS_START)
length:CPTDecimalFromFloat((axisEnd - AXIS_START)+5)];
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)self.graph.axisSet;
//set axes' title, labels and their text styles
CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
textStyle.fontName = #"Helvetica";
textStyle.fontSize = 14;
textStyle.color = [CPTColor whiteColor];
if (graphType == #"TotalProject"){
axisSet.xAxis.title = #"Project Name";
}
else if (graphType == #"TotalCategory"){
axisSet.xAxis.title = #"Category Name";
}
else if (graphType == #"TotalCurrency"){
axisSet.xAxis.title = #"Currency Name";
}
else if (graphType == #"DistanceTravelled"){
axisSet.xAxis.title = #"Project";
}
else if (graphType == #"FuelCostProject"){
axisSet.xAxis.title = #"Project";
}
else if (graphType == #"FuelCostCurrency"){
axisSet.xAxis.title = #"Currency";
}
axisSet.yAxis.title = #"Total Value";
axisSet.xAxis.titleTextStyle = textStyle;
axisSet.yAxis.titleTextStyle = textStyle;
axisSet.xAxis.titleOffset = 50.0f;
axisSet.yAxis.titleOffset = 50.0f;
axisSet.xAxis.labelTextStyle = textStyle;
axisSet.xAxis.labelOffset = 3.0f;
axisSet.yAxis.labelTextStyle = textStyle;
axisSet.yAxis.labelOffset = 3.0f;
//set axes' line styles and interval ticks
CPTMutableLineStyle *lineStyle = [CPTMutableLineStyle lineStyle];
lineStyle.lineColor = [CPTColor whiteColor];
lineStyle.lineWidth = 3.0f;
axisSet.xAxis.axisLineStyle = lineStyle;
axisSet.yAxis.axisLineStyle = lineStyle;
axisSet.xAxis.majorTickLineStyle = lineStyle;
axisSet.yAxis.majorTickLineStyle = lineStyle;
//Set x axis tick length to 0 as there is no data on the x axis
axisSet.xAxis.majorIntervalLength = CPTDecimalFromFloat(0.0f);
if (axisEnd <= 400){
axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(25.0f);
}
else if (axisEnd <= 900){
axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(50.0f);
}
else if (axisEnd <= 1300){
axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(75.0f);
}
else if (axisEnd <= 1800){
axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(100.0f);
}
else if (axisEnd <= 2300){
axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(125.0f);
}
else if (axisEnd <= 2800){
axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(150.0f);
}
else if (axisEnd <= 3300){
axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(175.0f);
}
else if (axisEnd <= 3500){
axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(200.0f);
}
else {
axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(300.0f);
}
axisSet.xAxis.majorTickLength = 7.0f;
axisSet.yAxis.majorTickLength = 7.0f;
axisSet.xAxis.minorTickLineStyle = lineStyle;
axisSet.yAxis.minorTickLineStyle = lineStyle;
axisSet.xAxis.minorTicksPerInterval = 1;
axisSet.yAxis.minorTicksPerInterval = 1;
axisSet.xAxis.minorTickLength = 5.0f;
axisSet.yAxis.minorTickLength = 5.0f;
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMaximumFractionDigits:2];
[numberFormatter setPositiveFormat:#"###0.00"];
axisSet.yAxis.labelFormatter = numberFormatter;
int initialTickLocation = 9;
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSMutableArray *customTickLocations = [[NSMutableArray alloc] init];
NSMutableArray *xAxisLabels = [[NSMutableArray alloc] init];
if (graphType == #"TotalProject"){
for (int i = 0; i < [appDelegate.projects count]; i++){
//CHANGE THESE NUMBERS TO CHANGE POSITIONS OF THE LABELS
[customTickLocations addObject:[NSNumber numberWithInt:initialTickLocation]];
initialTickLocation = initialTickLocation + 7;
[xAxisLabels addObject:[[appDelegate.projects objectAtIndex:i] name]];
}
}
else if (graphType == #"TotalCategory"){
for (int i = 0; i < [appDelegate.categories count]; i++){
//CHANGE THESE NUMBERS TO CHANGE POSITIONS OF THE LABELS
[customTickLocations addObject:[NSNumber numberWithInt:initialTickLocation]];
initialTickLocation = initialTickLocation + 7;
[xAxisLabels addObject:[[appDelegate.categories objectAtIndex:i] name]];
}
}
else if (graphType == #"TotalCurrency"){
for (int i = 0; i < [appDelegate.currencies count]; i++){
//CHANGE THESE NUMBERS TO CHANGE POSITIONS OF THE LABELS
[customTickLocations addObject:[NSNumber numberWithInt:initialTickLocation]];
initialTickLocation = initialTickLocation + 7;
[xAxisLabels addObject:[[appDelegate.currencies objectAtIndex:i] shortName]];
}
}
else if (graphType == #"DistanceTravelled"){
for (int i = 0; i < [appDelegate.projects count]; i++){
//CHANGE THESE NUMBERS TO CHANGE POSITIONS OF THE LABELS
[customTickLocations addObject:[NSNumber numberWithInt:initialTickLocation]];
initialTickLocation = initialTickLocation + 7;
[xAxisLabels addObject:[[appDelegate.projects objectAtIndex:i] name]];
}
}
else if (graphType == #"FuelCostProject"){
for (int i = 0; i < [appDelegate.projects count]; i++){
//CHANGE THESE NUMBERS TO CHANGE POSITIONS OF THE LABELS
[customTickLocations addObject:[NSNumber numberWithInt:initialTickLocation]];
initialTickLocation = initialTickLocation + 7;
[xAxisLabels addObject:[[appDelegate.projects objectAtIndex:i] name]];
}
}
else if (graphType == #"FuelCostCurrency"){
for (int i = 0; i < [appDelegate.currencies count]; i++){
//CHANGE THESE NUMBERS TO CHANGE POSITIONS OF THE LABELS
[customTickLocations addObject:[NSNumber numberWithInt:initialTickLocation]];
initialTickLocation = initialTickLocation + 7;
[xAxisLabels addObject:[[appDelegate.currencies objectAtIndex:i] shortName]];
}
}
axisSet.xAxis.labelRotation = M_PI/4;
axisSet.xAxis.labelingPolicy = CPTAxisLabelingPolicyNone;
NSUInteger labelLocation = 0;
NSMutableArray *customLabels = [NSMutableArray arrayWithCapacity:[xAxisLabels count]];
for (NSNumber *tickLocation in customTickLocations){
CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText:[xAxisLabels objectAtIndex:labelLocation++] textStyle:axisSet.xAxis.labelTextStyle];
newLabel.tickLocation = [tickLocation decimalValue];
newLabel.offset = axisSet.xAxis.labelOffset + axisSet.xAxis.majorTickLength;
newLabel.rotation = M_PI / 4;
[customLabels addObject:newLabel];
}
axisSet.xAxis.axisLabels = [NSSet setWithArray:customLabels];
// Create bar plot and add it to the graph
CPTBarPlot *plot = [[CPTBarPlot alloc] init] ;
plot.dataSource = self;
plot.delegate = self;
plot.barWidth = [[NSDecimalNumber decimalNumberWithString:#"5.0"]
decimalValue];
plot.barOffset = [[NSDecimalNumber decimalNumberWithString:#"10.0"]
decimalValue];
plot.barCornerRadius = 5.0;
// Remove bar outlines
CPTMutableLineStyle *borderLineStyle = [CPTMutableLineStyle lineStyle];
borderLineStyle.lineColor = [CPTColor clearColor];
plot.lineStyle = borderLineStyle;
// Identifiers are handy if you want multiple plots in one graph
plot.identifier = #"projectTotals";
[self.graph addPlot:plot];
}
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
return [self.data count];
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSDictionary *bar = [self.data objectAtIndex:index];
if(fieldEnum == CPTBarPlotFieldBarLocation){
NSLog(#"Position: %#", [bar valueForKey:BAR_POSITION]);
return [bar valueForKey:BAR_POSITION];
}
else{
NSLog(#"Height: %#", [bar valueForKey:BAR_HEIGHT]);
return [bar valueForKey:BAR_HEIGHT];
}
}
-(CPTLayer *)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)index
{
CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
textStyle.fontName = #"Helvetica";
textStyle.fontSize = 12;
textStyle.color = [CPTColor whiteColor];
NSDictionary *bar = [self.data objectAtIndex:index];
//Here we want to display the value for that day, not the name of the day
CPTTextLayer *label = [[CPTTextLayer alloc] initWithText:[NSString stringWithFormat:#"%0.2f", [[bar valueForKey:BAR_HEIGHT] floatValue]]];
label.textStyle =textStyle;
return label;
}
-(CPTFill *)barFillForBarPlot:(CPTBarPlot *)barPlot
recordIndex:(NSUInteger)index
{
NSDictionary *bar = [self.data objectAtIndex:index];
CPTGradient *gradient = [CPTGradient gradientWithBeginningColor:[CPTColor whiteColor]
endingColor:[bar valueForKey:#"COLOR"]
beginningPosition:0.0 endingPosition:0.3 ];
[gradient setGradientType:CPTGradientTypeAxial];
[gradient setAngle:320.0];
CPTFill *fill = [CPTFill fillWithGradient:gradient];
return fill;
}
- (void)dealloc
{
}
- (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
- (void)viewDidLoad
{
[super viewDidLoad];
self.data = [NSMutableArray array];
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
count = [appDelegate.projects count];
int catCount = [appDelegate.categories count];
int currencyCount = [appDelegate.currencies count];
int bar_heights[count];
NSString *categories[count];
int catBar_heights[catCount];
NSString *catCategories[catCount];
int currencyBar_heights[currencyCount];
NSString *currencyCategories[currencyCount];
if ([graphType isEqualToString:#"TotalProject"])
{
for (int i = 0; i < count; i++)
{
TotalValueCalculator *calc = [[TotalValueCalculator alloc] initWithString:[[appDelegate.projects objectAtIndex:i] name]];
NSString *totalValueString = [calc compareProject];
float totalValue = [totalValueString floatValue];
bar_heights[i] = totalValue;
NSLog(#"---%0.2f", totalValue);
categories[i] = [[appDelegate.projects objectAtIndex:i] name];
}
axisEnd = findMax(bar_heights, count) + ((findMax(bar_heights, count)) / 10);
UIColor *colors[] = {
[UIColor colorWithRed:139/255.0 green:198/255.0 blue:63/255.0 alpha:1],
nil};
for (int i = 0; i < [appDelegate.projects count] ; i++){
int position = i*7; //Bars will be 7 pts away from each other
float height = bar_heights[i];
NSDictionary *bar = [NSDictionary dictionaryWithObjectsAndKeys:
[NSDecimalNumber numberWithFloat:position],BAR_POSITION,
[NSDecimalNumber numberWithFloat:height],BAR_HEIGHT,
colors[0],COLOR,
categories[i],CATEGORY,
nil];
NSLog(#"^^^^^^^^^^^^^%#", [NSDecimalNumber numberWithFloat:height]);
[self.data addObject:bar];
}
}
else if ([graphType isEqualToString:#"TotalCategory"])
{
for (int i = 0; i < catCount; i++)
{
TotalValueCalculator *calc = [[TotalValueCalculator alloc] initWithString:[[appDelegate.categories objectAtIndex:i] name]];
NSString *totalValueString = [calc compareCategory];
double totalValue = [totalValueString doubleValue];
catBar_heights[i] = totalValue;
catCategories[i] = [[appDelegate.categories objectAtIndex:i] name];
}
axisEnd = findMax(catBar_heights, catCount) + ((findMax(catBar_heights, catCount)) / 10);
UIColor *colors[] = {
[UIColor colorWithRed:236/255.0 green:139/255.0 blue:34/255.0 alpha:1],
nil};
for (int i = 0; i < [appDelegate.categories count] ; i++){
double position = i*7; //Bars will be 7 pts away from each other
double height = catBar_heights[i];
NSDictionary *bar = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithDouble:position],BAR_POSITION,
[NSNumber numberWithDouble:height],BAR_HEIGHT,
colors[0],COLOR,
catCategories[i],CATEGORY,
nil];
[self.data addObject:bar];
}
}
else if ([graphType isEqualToString:#"TotalCurrency"])
{
for (int i = 0; i < currencyCount; i++)
{
TotalValueCalculator *calc = [[TotalValueCalculator alloc] initWithString:[[appDelegate.currencies objectAtIndex:i] shortName]];
NSString *totalValueString = [calc compareCurrency];
double totalValue = [totalValueString doubleValue];
currencyBar_heights[i] = totalValue;
currencyCategories[i] = [[appDelegate.currencies objectAtIndex:i] shortName];
}
axisEnd = findMax(currencyBar_heights, currencyCount) + ((findMax(currencyBar_heights, currencyCount)) / 10);
UIColor *colors[] = {
[UIColor colorWithRed:236/255.0 green:139/255.0 blue:34/255.0 alpha:1],
nil};
for (int i = 0; i < [appDelegate.currencies count] ; i++){
double position = i*7; //Bars will be 7 pts away from each other
double height = currencyBar_heights[i];
NSDictionary *bar = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithDouble:position],BAR_POSITION,
[NSNumber numberWithDouble:height],BAR_HEIGHT,
colors[0],COLOR,
currencyCategories[i],CATEGORY,
nil];
[self.data addObject:bar];
}
}
else if ([graphType isEqualToString:#"DistanceTravelled"])
{
for (int i = 0; i < count; i++)
{
TotalValueCalculator *calc = [[TotalValueCalculator alloc] initWithString:[[appDelegate.projects objectAtIndex:i] name]];
NSString *totalValueString = [calc compareProjectDistance];
double totalValue = [totalValueString doubleValue];
bar_heights[i] = totalValue;
categories[i] = [[appDelegate.projects objectAtIndex:i] name];
}
axisEnd = findMax(bar_heights, count) + ((findMax(bar_heights, count)) / 10);
UIColor *colors[] = {
[UIColor colorWithRed:236/255.0 green:139/255.0 blue:34/255.0 alpha:1],
nil};
for (int i = 0; i < [appDelegate.projects count] ; i++){
double position = i*7; //Bars will be 7 pts away from each other
double height = bar_heights[i];
NSDictionary *bar = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithDouble:position],BAR_POSITION,
[NSNumber numberWithDouble:height],BAR_HEIGHT,
colors[0],COLOR,
categories[i],CATEGORY,
nil];
[self.data addObject:bar];
}
}
else if ([graphType isEqualToString:#"FuelCostProject"])
{
for (int i = 0; i < count; i++)
{
TotalValueCalculator *calc = [[TotalValueCalculator alloc] initWithString:[[appDelegate.projects objectAtIndex:i] name]];
NSString *totalValueString = [calc compareProjectFuel];
double totalValue = [totalValueString doubleValue];
bar_heights[i] = totalValue;
categories[i] = [[appDelegate.projects objectAtIndex:i] name];
}
axisEnd = findMax(bar_heights, count) + ((findMax(bar_heights, count)) / 10);
UIColor *colors[] = {
[UIColor colorWithRed:236/255.0 green:139/255.0 blue:34/255.0 alpha:1],
nil};
for (int i = 0; i < [appDelegate.projects count] ; i++){
double position = i*7; //Bars will be 7 pts away from each other
double height = bar_heights[i];
NSDictionary *bar = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithDouble:position],BAR_POSITION,
[NSNumber numberWithDouble:height],BAR_HEIGHT,
colors[0],COLOR,
categories[i],CATEGORY,
nil];
[self.data addObject:bar];
}
}
else if ([graphType isEqualToString:#"FuelCostCurrency"])
{
for (int i = 0; i < currencyCount; i++)
{
TotalValueCalculator *calc = [[TotalValueCalculator alloc] initWithString:[[appDelegate.currencies objectAtIndex:i] shortName]];
NSString *totalValueString = [calc compareCurrencyFuel];
double totalValue = [totalValueString doubleValue];
currencyBar_heights[i] = totalValue;
currencyCategories[i] = [[appDelegate.currencies objectAtIndex:i] shortName];
}
axisEnd = findMax(currencyBar_heights, currencyCount) + ((findMax(currencyBar_heights, currencyCount)) / 10);
UIColor *colors[] = {
[UIColor colorWithRed:236/255.0 green:139/255.0 blue:34/255.0 alpha:1],
nil};
for (int i = 0; i < [appDelegate.currencies count] ; i++){
double position = i*7; //Bars will be 7 pts away from each other
double height = currencyBar_heights[i];
NSDictionary *bar = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithDouble:position],BAR_POSITION,
[NSNumber numberWithDouble:height],BAR_HEIGHT,
colors[0],COLOR,
currencyCategories[i],CATEGORY,
nil];
[self.data addObject:bar];
}
}
[self generateBarPlot];
}
- (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
I know theres a lot there, but I just can't figure out for the life of me how I get this bar chart to display float values (for bar heights)? I've spent so much time on this now I'm starting to despair.
Does anyone know how to do this? The values that chart is receiving are definitely float values.
Any help at all would be much appreciated..
Thanks a lot,
Jack
The bar_heights arrays in -viewDidLoad are declared as int. Since the data values are stored here before being placed in the dictionary structure you pass to the plot datasource, any fractional part of the values gets lost.

NSTimer stops when we click on ScrollView

In my app am using UIScrollView which is having UIImageView(20) to add images iused the - (void)populateScrollView method.
- (void)populateScrollView
{
TonifyAppDelegate *appDelegate = (TonifyAppDelegate *)[UIApplication sharedApplication].delegate;
double x1 = 0, y1 = 3;
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
NSMutableArray *getEffectsImageData = [ud objectForKey:#"getimageeffects"];
imageViewsArray = [[NSMutableArray alloc] initWithCapacity:[getEffectsImageData count]];
for(int i = 0; i < [getEffectsImageData count]; i++)
{
NSString *sfxUrlFileName = [ [getEffectsImageData objectAtIndex:i] lastPathComponent];
NSLog(#"sfxUrlFileName: %#", sfxUrlFileName);
NSData *imageData = [appDelegate readSongDataFromDocsDirectory:sfxUrlFileName];
UIImage *image = [[UIImage alloc] initWithData:imageData];
UIImageView *anImageView = [[UIImageView alloc]initWithImage:image];
CGRect imageFrame = anImageView.frame;
imageFrame.origin.x = x1;
imageFrame.origin.y = y1;
anImageView.frame = CGRectMake(x1, y1, 45, 41);
anImageView.userInteractionEnabled = YES;
[scrollView addSubview:anImageView];
x1 += anImageView.frame.size.width + 3;
if (anImageView && [anImageView isMemberOfClass: [UIImageView class]])
[imageViewsArray addObject: anImageView];
}
NSLog(#"imageViewsArray:%#",imageViewsArray);
}
And to recognize touch in UIScrollView i used
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(singleTapGestureCaptured:)];
[scrollView addGestureRecognizer:singleTap];
Meanwhile am running song by using NSTimer which is like
myTimer = [NSTimer scheduledTimerWithTimeInterval:timeinterval target:self selector:#selector(**updatplayer**) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:myTimer forMode:NSRunLoopCommonModes];
in updatePlayer method am doing task as follows
- (void)updatplayer
{
TonifyAppDelegate *appDelegate = (TonifyAppDelegate *)[UIApplication sharedApplication].delegate;
if (mThresholdVal<mMainLoopLength)
{
mThresholdVal+=0.5;
}
else
{
mThresholdVal = 0.0;
}
if (divimageView)
{
[divimageView removeFromSuperview];
}
if ([self isHeadsetPluggedIn]==NO) {
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);
}
else
{
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_None;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);
}
NSString *cu=[NSString stringWithFormat:#"%2.f",audioPlayer.currentTime];
NSString *du=[NSString stringWithFormat:#"%2.f",audioPlayer.duration];
NSLog(#"LOOP cu Duration = %#",cu);
NSLog(#"LOOP du = %#",du);
int curenttime=(int)[cu intValue];
NSLog(#"LOOP current Duration = %2.f",audioPlayer.duration);
if(curenttime==0)
{
[audioPlayer play];
x=20;
}
mixdata = [NSMutableDictionary dictionary];
{
[activityIndicator stopAnimating];
activityIndicator.hidden = YES;
[divimageView setFrame:CGRectMake(x, 87, 12, 144)];
[self.view addSubview:divimageView];
x=x+1;
if ((x>19 && x< 480) && appDelegate.songURL != NULL) {
[avplayer play];
NSLog(#"mixdata:%#", mixdata);
}
else if((x>19 && x< 480) && (appDelegate.songIntroUrl || appDelegate.songMidUrl || appDelegate.songChorusUrl) )
{
[audioPlayer play];
}
if (x==xCord && yCord<235)
{
[audioPlayer1 play];
}
if (x==recXcord)
{
recaudioPlayer.volume = 10.0;
[recaudioPlayer play];
[activityIndicator stopAnimating];
activityIndicator.hidden = YES;
}
if(appDelegate.xCordArray!=NULL && [appDelegate.tagArray count]>0)
{
for(int i = 0; i<[appDelegate.xCordArray count];i++)
{
if (i == 0){
NSLog(#"sfxCount in i==0......%d",sfxCount);
NSLog(#"[appDelegate.xCordArray count] in i==0......%d",[appDelegate.xCordArray count]);
NSLog(#"[appDelegate.mMixedSFXTrack2Array count] in i==0......%d",[appDelegate.mMixedSFXTrack2Array count]);
if (sfxCount-1 != [appDelegate.xCordArray count])
{
if ([appDelegate.xCordArray count] > [appDelegate.mMixedSFXTrack2Array count] )
{
mShouldBufferUpdate = TRUE;
sfxCount = [appDelegate.xCordArray count];
}
}
}
if (x==[[appDelegate.xCordArray objectAtIndex:i] intValue] && appDelegate.imgDragXCodr<480)
{
int j = [[appDelegate.tagArray objectAtIndex:i] intValue];
//mShouldBufferUpdate = TRUE;
[self getSetSongData:j :x];
[audioPlayer2 play];
}
}
}
if(appDelegate.xCordTrack3Array!=NULL && [appDelegate.track3tagArray count]>0)
{
for(int i = 0; i<[appDelegate.xCordTrack3Array count];i++)
{
if (i == 0)
{
if (sfxCount3-1 != [appDelegate.xCordTrack3Array count])
{
if ([appDelegate.xCordTrack3Array count] > [appDelegate.mMixedSFXTrack3Array count] )
{
mShouldBuffer3Update = TRUE;
sfxCount3 = [appDelegate.xCordTrack3Array count];
}
}
}
if (x==[[appDelegate.xCordTrack3Array objectAtIndex:i] intValue] && appDelegate.imgDragXCodr1<480)
{
int j = [[appDelegate.track3tagArray objectAtIndex:i] intValue];
[self getSetSongData:j :x];
[trac3AudioPlayer play]; //For SFX Sounds
}
}
}
if (x == 480)
{
x=20;
}
}
}
When i click on scrollView it generates an image in UIView(main View) at that time NSTimer is getting paused.
How can we solve this.
Any one can help or suggest me.
Thanks in advance.

Drawing route partially not getting required output in iPhone MapView

I am trying to draw route between two points using polyline . I got somewhat route but not correct and I think it will get confused at the turn . I am using google api for getting points of route .Following is code what i tried please check .
- (IBAction)onclickDrawButton:(id)sender
{
flag=TRUE;
NSString *startpoint=[satrtTextfield text];
NSString *endpoint=[endTextfield text];
NSMutableString *urlString=[NSMutableString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=%#&destination=%#&sensor=false",startpoint,endpoint];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
delegate:self];
if(connection)
{
NSLog(#"connectin done");
}
}
-(void)connection:(NSURLConnection*)connection didReceiveResponse: (NSURLResponse*)response
{
if(flag)
{
recievedRoutes=[[NSMutableData alloc]init];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if(flag){
NSString *jsonResult = [[NSString alloc] initWithData:recievedRoutes encoding:NSUTF8StringEncoding];
NSLog(#"json response %#",jsonResult);
NSDictionary *partialJsonDict=[jsonResult JSONValue];
NSArray *items=[partialJsonDict valueForKey:#"routes"];
//NSLog(#"responsed valued %#",[[items objectAtIndex:0]valueForKey:#"legs"]);
NSArray *aary=[[items objectAtIndex:0]valueForKey:#"legs"];
NSLog(#"legs array wuth polyline %#",[[aary objectAtIndex:0]valueForKey:#"steps"]);
NSArray *steps=[[aary objectAtIndex:0]valueForKey:#"steps"];
NSLog(#"steps %#",[[steps objectAtIndex:1]objectForKey:#"polyline"]);
NSMutableString *string=[[NSMutableString alloc]init];
for(int i=0;i<[steps count];i++)
{
//NSLog(#"steps i value %#",[[[steps objectAtIndex:i]objectForKey:#"polyline"]objectForKey:#"sttpoints"]);
[string appendString:[[[steps objectAtIndex:i]objectForKey:#"polyline"]objectForKey:#"points"]];
}
NSLog(#"final %#",string);
MKPolyline *polyline=[self polylineWithEncodedString:string];
[mapView addOverlay:polyline];
[self zoomToFitMapAnnotations:mapView];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
if(flag){
[recievedRoutes appendData:data];
}
}
//to decode polyline and retrives coordintes i have used following method
-(MKPolyline *)polylineWithEncodedString:(NSString *)encodedString {
const char *bytes = [encodedString UTF8String];
NSUInteger length = [encodedString lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
NSUInteger idx = 0;
NSUInteger count = length / 4;
CLLocationCoordinate2D *coords = calloc(count, sizeof(CLLocationCoordinate2D));
NSUInteger coordIdx = 0;
float latitude = 0;
float longitude = 0;
while (idx < length) {
char byte = 0;
int res = 0;
char shift = 0;
do {
byte = bytes[idx++] - 63;
res |= (byte & 0x1F) << shift;
shift += 5;
} while (byte >= 0x20);
float deltaLat = ((res & 1) ? ~(res >> 1) : (res >> 1));
latitude += deltaLat;
shift = 0;
res = 0;
do {
byte = bytes[idx++] - 0x3F;
res |= (byte & 0x1F) << shift;
shift += 5;
} while (byte >= 0x20);
float deltaLon = ((res & 1) ? ~(res >> 1) : (res >> 1));
longitude += deltaLon;
float finalLat = latitude * 1E-5;
float finalLon = longitude * 1E-5;
CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(finalLat, finalLon);
coords[coordIdx++] = coord;
NSLog(#"in encoding %f %f ",latitude,longitude);
if (coordIdx == count) {
NSUInteger newCount = count + 10;
coords = realloc(coords, newCount * sizeof(CLLocationCoordinate2D));
count = newCount;
}
}
MKPolyline *polyline = [MKPolyline polylineWithCoordinates:coords count:coordIdx];
free(coords);
return polyline;
}
// to draw actual route
- (MKOverlayView *)mapView:(MKMapView *)mapView
viewForOverlay:(id<MKOverlay>)overlay {
MKPolylineView *overlayView = [[MKPolylineView alloc] initWithOverlay:overlay];
overlayView.lineWidth = 2;
overlayView.strokeColor = [UIColor purpleColor];
overlayView.fillColor = [[UIColor purpleColor] colorWithAlphaComponent:0.1f];
return overlayView;
}
After your line
NSArray *steps=[[aary objectAtIndex:0]valueForKey:#"steps"];
replace lines with this may work
NSMutableArray *polyLinesArray = [[NSMutableArray alloc] init];
for (int i = 0; i < [steps count]; i++)
{
NSString* encodedPoints = [[[steps objectAtIndex:i] objectForKey:#"polyline"] valueForKey:#"points"];
MKPolyline *route = [self polylineWithEncodedString:encodedPoints];
[polyLinesArray addObject:route];
}
[self.mapView addOverlays:polyLinesArray];
[polyLinesArray release];