NSTimer stops when we click on ScrollView - iphone

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.

Related

UIScrollView has White Space above SubViews

I am running across a weird issue, which I can't seem to figure out.
Upon adding multiple SubViews to a ScrollView, the ScrollViews keeps on adding a White Space ontop of the regular image
A bit better with more colors:
This is how it should look like:
The Image is perfectly scrollable.
This is the code I'm using to create the scrollview:
-(void)addImagesToScrollView
{
if (self.product != nil)
{
int imageCount = 0;
if (self.product.labelImage != nil)
{
UIImageView *labelImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height)];
labelImage.image = [UIImage imageWithData:self.product.labelImage];
labelImage.contentMode = UIViewContentModeScaleAspectFit;
labelImage.tag = 100;
[self.scrollView addSubview:labelImage];
imageCount += 1;
}
if (self.product.bottleImage != nil)
{
UIImageView *bottleImage = [[UIImageView alloc] initWithFrame:CGRectMake(self.scrollView.frame.size.width, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height)];
bottleImage.image = [UIImage imageWithData:self.product.bottleImage];
bottleImage.contentMode = UIViewContentModeScaleAspectFit;
bottleImage.tag = 101;
imageCount += 1;
[self.scrollView addSubview:bottleImage];
}
if (self.product.pourImage != nil)
{
UIImageView *pourImage = [[UIImageView alloc] initWithFrame:CGRectMake(self.scrollView.frame.size.width * 2, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height)];
pourImage.image = [UIImage imageWithData:self.product.pourImage];
pourImage.contentMode = UIViewContentModeScaleAspectFit;
pourImage.tag = 102;
imageCount += 1;
[self.scrollView addSubview:pourImage];
}
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * imageCount, self.scrollView.frame.size.height);
[self.scrollView setContentOffset:CGPointZero animated:NO];
}
}
Edit:
With a BackgroundColor:
use:
bottleImage.layer.color = [UIcolor blueColor].CGColor;
bottleImage.layer.borderWidth = 2.0f;
It will let you see the frame of your UIImageView maybe you are calculating incorrectly the frame
Use below code and you will get desired output. In the following code you app will use album photos and automatically sets size of the scrolling as per the number of images in album. And please modify according to your image repository.
-(void)getAllPictures
{
imageArray=[[NSArray alloc] init];
mutableArray =[[NSMutableArray alloc]init];
NSMutableArray* assetURLDictionaries = [[NSMutableArray alloc] init];
library = [[ALAssetsLibrary alloc] init];
void (^assetEnumerator)( ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
if(result != nil) {
if([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]) {
[assetURLDictionaries addObject:[result valueForProperty:ALAssetPropertyURLs]];
NSURL *url= (NSURL*) [[result defaultRepresentation]url];
[library assetForURL:url
resultBlock:^(ALAsset *asset) {
[mutableArray addObject:[UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage]]];
if ([mutableArray count]==count)
{
imageArray=[[NSArray alloc] initWithArray:mutableArray];
[self allPhotosCollected:imageArray];
}
}
failureBlock:^(NSError *error){ NSLog(#"operation was not successfull!"); } ];
}
}
};
NSMutableArray *assetGroups = [[NSMutableArray alloc] init];
void (^ assetGroupEnumerator) ( ALAssetsGroup *, BOOL *)= ^(ALAssetsGroup *group, BOOL *stop) {
if(group != nil) {
[group enumerateAssetsUsingBlock:assetEnumerator];
[assetGroups addObject:group];
count=[group numberOfAssets];
}
};
assetGroups = [[NSMutableArray alloc] init];
[library enumerateGroupsWithTypes:ALAssetsGroupAll
usingBlock:assetGroupEnumerator
failureBlock:^(NSError *error) {NSLog(#"There is an error");}];
}
-(void)allPhotosCollected:(NSArray*)imgArray
{
CGSize imageSize;
imageSize.width= imageView.bounds.size.width;
imageSize.height = imageView.bounds.size.height;
self.scrollView=[[UIScrollView alloc]init];
self.scrollView.frame = imageView.frame;
self.scrollView.contentSize = CGSizeMake(imageSize.width * imgArray.count, imageSize.height);
self.scrollView.pagingEnabled = YES;
self.scrollView.bounces=YES;
self.scrollView.scrollEnabled = YES;
self.scrollView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin;
[self.scrollView flashScrollIndicators];
[self.view addSubview:self.scrollView];
CGFloat xPos = 0.0;
for (UIImage *image in imgArray) {
imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(xPos, 0.0, imageSize.width, imageSize.height);
[self.scrollView addSubview:imageView];
xPos += imageSize.width;
// assuming ARC, otherwise release imageView
}
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 20,320 , 420)];
[self getAllPictures];
}

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];
}
}
}

iphone textview update while cycle running thread

I'm trying to create a typewriter effect.
my code works fine. My problem, and this ... UITextView fails to update in real time. this is my code:
NSMutableArray *testochar=[util getTestoChar:value];
for (int i=0; i<[testochar count]; i++){
NSString *y=[testochar objectAtIndex:i];
[NSThread sleepForTimeInterval:0.1f];
self.txtview.text=[self.txtview.text stringByAppendingString:y];
}
All modification on UI you should do in main thread, try use performSelectorOnMainThread:withObject:waitUntilDone:
call
//...
for(int i=0;i<[testochar count];i++){
NSString *y=[testochar objectAtIndex:i];
[NSThread sleepForTimeInterval:0.1f];
NSDictionary *arg = [NSDictionary dictionaryWithObjectAndKeys:
self.txtview, #"textView",
y, #"string", nil ];
[self performSelectorOnMainThread:#selector(updateTextForTextView:) withObject:arg waitUntilDone:NO];
}
//.....
-(void)updateTextForTextView:(NSDictionary*)arg {
NSString *string = [arg objectForKey:#"string"];
UITextView *textView = [arg objectForKey:#"textView"];
self.txtview.text=[self.txtview.text stringByAppendingString:string];
}
(update)
try
- (void)viewDidLoad {
[super viewDidLoad];
textView.text = #"";
[[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(update) userInfo:nil repeats:YES] retain];
}
-(void) update {
static char text[] = "HELLO";
static int i =0;
if (text[i%6]==0) {
textView.text = [NSString stringWithFormat:#""];
} else {
textView.text = [NSString stringWithFormat:#"%#%c", textView.text, text[i%6] ];
}
i++;
}
it works like:
http://www.youtube.com/watch?v=tB2YKX4zpY4
really thanks for your advice. I did it by modifying the code this way.
1) self.timer = [[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(update) userInfo:nil repeats:YES] retain];
-(void) update {
char text[[self.testo length]];
for(int i=0;i<self.testo.length;i++){
text[i]=[self.testo characterAtIndex:i];
}
static int i =0;
if (i==self.testo.length) {
/// txtview.text = [NSString stringWithFormat:#""];
[self.timer invalidate];
} else {
txtview.text = [NSString stringWithFormat:#"%#%c", txtview.text, text[i%self.testo.length] ];
}
i++;
}

problem with uiimageView collision detection

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 ?