I want to change label.text but when I do it and check it with a NSLog it returns me a (null).
Here's my code:
NextViewController.h
#interface NextViewController (){
NSTimer *timerTen;
NSInteger countDown;
NSString *timer;
}
#end
#implementation NextViewController
static UILabel *lblTest;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)startCountDown{
countDown = 10;
timerTen = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(dismissView) userInfo:nil repeats:YES];
}
-(void)dismissView{
timer = [NSString stringWithFormat:#"%ld", (long)countDown];
_lbl_countDown.text = timer;
NSLog(#"\nCountDown: %#\n", self.lbl_countDown.text);
countDown--;
if (countDown <= 0) {
SectionViewController *sectionView = [[SectionViewController alloc] init];
[sectionView.presentedViewController dismissViewControllerAnimated:YES completion:nil];
}
}
Then I have a XIB file with a label and more things, so I've used a prop right there in the .h to change it from other classes, but I can't change it.
NextViewController.h
#import <UIKit/UIKit.h>
#interface NextViewController : UIViewController
#property (strong, nonatomic) IBOutlet UILabel *lbl_section;
#property (strong, nonatomic) IBOutlet UILabel *lbl_nextSection;
#property (strong, nonatomic) IBOutlet UILabel *lbl_countDown;
-(void)startCountDown;
#end
Hope anyone can help me cause I don't know what is happening here.
Thanks.
Call your method in ViewDidLoad or ViewWillAppear
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
[self startCountDown]
}
OR
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self startCountDown]
}
Try to call the function first using [self startCountDown] in the ViewDidLoad method
if the problem persist:
Try to use this : [_lbl_count setText#"myText"];
In the Identity Inspector, click on the label uncheck the 'Static Text' and check 'Enabled' and 'User Interaction Enabled'
Finally check that your variable timer is not null after your initialization.
timer = [NSString stringWithFormat:#"%ld", (long)countDown];
Hope that will be helpfull
I wrote this code to use a button tap to start a countdown from 10 to a segue:
In my h:
#property (strong, nonatomic) IBOutlet UILabel *countdownCounter;
#property (strong, nonatomic) IBOutlet UIButton *countdownStarter;
In my m:
static NSTimer *timer;
static int remainingCounts;
.
.
-(void)countDown
{
if (--remainingCounts == 0)
{
[timer invalidate];
timer = nil;
[self performSegueWithIdentifier:#"FromStartToBalancer" sender:self];
}
else
{
NSString * holdText = [NSString stringWithFormat:#"%d", remainingCounts];
[self.countdownCounter setText:holdText];
}
}
- (IBAction)goToBalancerPressed:(UIButton *)sender
{
self.countdownStarter.userInteractionEnabled = NO;
self.countdownStarter.alpha = .3;
remainingCounts = 10;
timer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:#selector(countDown)
userInfo:nil
repeats:YES];
}
Related
I want a ranking in my app where you can see who has the fastest lap.
I try to convert the time into milliseconds, but it didn't work well.
This is my code at the moment.
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize watch,start,reset;
- (void)viewDidLoad {
[super viewDidLoad];
running = NO;
count = 0;
watch.text = #"00:00.00";
start.layer.cornerRadius = 45;
reset.layer.cornerRadius = 45;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (IBAction)startpressed:(id)sender {
if (running == NO) {
running = YES;
[start setTitle:#"STOPP" forState:UIControlStateNormal];
NSDate *watch = [NSDate dateWithTimeIntervalSince1970:(1273636800 / 1000.0)];
if (myTimer == nil) {
myTimer = [NSTimer scheduledTimerWithTimeInterval:0.0055
target:self
selector:#selector(updateTimer)
userInfo: nil
repeats:YES];
}
} else {
running = NO;
[myTimer invalidate];
myTimer = nil;
[start setTitle:#"START" forState:UIControlStateNormal];
}
}
- (IBAction)resetpressed:(id)sender {
running =NO;
[myTimer invalidate];
myTimer =nil;
[start setTitle:#"START" forState:UIControlStateNormal];
count = 0;
watch.text = #"00:00.00";
}
- (void)updateTimer {
count++;
int min = floor(count/100/60);
int sec = floor(count/100);
int mSec = count % 100;
if (sec >= 60) {
sec = sec % 60;
}
watch.text = [NSString stringWithFormat:#"%02d:%02d.%02d", min,sec,mSec];
}
#end
this is my ViewController.h code:
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
{
NSTimer *myTimer;
BOOL running;
int count;
double methodStart;
}
#property (weak, nonatomic) IBOutlet UILabel *watch;
#property (weak, nonatomic) IBOutlet UIButton *start;
#property (weak, nonatomic) IBOutlet UIButton *reset;
#property (weak, nonatomic) IBOutlet UILabel *eins;
#property (weak, nonatomic) IBOutlet UILabel *zwei;
#property (weak, nonatomic) IBOutlet UILabel *drei;
- (IBAction)startpressed:(id)sender;
- (IBAction)resetpressed:(id)sender;
- (void) updateTimer;
#end
Create array for holding lap history in class interface/extension and initialise it.
self.lapHistory = [#[] mutableCopy];
Capture and sort every lap time when lap is reset/stopped
- (IBAction)resetpressed:(id)sender {
[self.lapHistory addObject:#(count)];
self.lapHistory = [self.lapHistory sortedArrayUsingSelector: #selector(compare:)];
}
Display sorted ranking from lapHistory
-(void)displayRanking{
NSMutableString *rankingResult = [[NSMutableString alloc] init];
for (NSNumber *lap in self.lapHistory) {
[rankingResult appendString:[NSString stringWithFormat:#"%ld\n",[lap integerValue]]];
}
NSLog(#"Ranking result is %#", rankingResult);
}
I have a UIPickerView with an array in one view controller and an NSTimer in another, i am trying to:
1) link the picker array to NSTimer so a user selects a time on the picker for image to self destruct
2) show time remaining in UILabel so seconds the user selects going down to 0. (ex. select 2 from picker label shows 2 then 1 then 0 and image destucts)
one vc.h
#property (strong, nonatomic) IBOutlet UIPickerView *timePicker;
#property (nonatomic, strong) NSArray *pickerData;
one vc.m
- (void)viewDidLoad {
[super viewDidLoad];
self.pickerData = #[#1,#2,#3,#4,#5,#6,#7];
self.timePicker.dataSource = self;
self.timePicker.delegate = self;
}
- (void) viewWillAppear:(BOOL)animated {
[self.textField setText:self.userText];
}
-(long)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
-(long)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return self.pickerData.count;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
[self.pickerData objectAtIndex:[self.timePicker selectedRowInComponent:0]];
}
two vc.h
#property (weak, nonatomic) IBOutlet UILabel *timeLabel;
#property (nonatomic, assign) int seconds;
two vc.m
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[NSTimer scheduledTimerWithTimeInterval:7 target:self selector:#selector(timeout)
userInfo:nil repeats:NO];
[NSTimer scheduledTimerWithTimeInterval:self.seconds target:self selector:#selector(setTimeToLabel) userInfo:nil repeats:NO];
}
-(void)timeout
{
// pops to root view
}
- (void)setTimeToLabel
{
self.seconds = self.seconds - 1;
self.timeLabel.text = [NSString stringWithFormat:#"%d", self.seconds];
}
the NSTimer does not respond to the self.seconds and does not pick up the user input from the UIPicker.
any ideas as to how I can link the picker to the timer so that the timer responds to the seconds the user selects in the picker and display the remaining seconds in the label??
my prepareforsegue method below:
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.destinationViewController isKindOfClass:[oneViewController class]]) {
oneViewController * ovc = (oneViewController*)segue.destinationViewController;
ovc.array = //whatever;
}
if ([segue.destinationViewController isEqual:#"secondVC"]) {
NSInteger row = [self.timePicker selectedRowInComponent:0];
twoViewController *tvc = [segue destinationViewController];
tvc.seconds = [[self.pickerData objectAtIndex:row] intValue];
}
}
what can be the issue with it, the onviewcontroller method works, whatever i pass it works, but for the tvc.seconds nothing is passed to it.
You are creating a new instance of the controller rather than the actual one that would be used. You should be using the prepareForSegue method to do this, and get a reference to the destinationViewController, like so:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqual: #"nextScreen"]) {
NSInteger row = [self.timePicker selectedRowInComponent:0];
SecondViewController *tvc = [segue destinationViewController];
tvc.seconds = [[self.pickerData objectAtIndex:row] intValue];
}
}
// First View Controller
//.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
#property (weak, nonatomic) IBOutlet UITextField *textField;
#property (weak, nonatomic) IBOutlet UIPickerView *timePicker;
#property (nonatomic, strong) NSArray *pickerData;
#property (weak, nonatomic) IBOutlet UIButton *next;
#end
//.m
#import "ViewController.h"
#import "SecondViewController.h"
#interface ViewController () <UIPickerViewDataSource, UIPickerViewDelegate>
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.pickerData = #[#1,#2,#3,#4,#5,#6,#7];
self.timePicker.dataSource = self;
self.timePicker.delegate = self;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return self.pickerData.count;
}
- (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [NSString stringWithFormat: #"%#", self.pickerData[row]];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
[self.pickerData objectAtIndex:[self.timePicker selectedRowInComponent:0]];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqual: #"nextScreen"]) {
NSInteger row = [self.timePicker selectedRowInComponent:0];
SecondViewController *tvc = [segue destinationViewController];
tvc.seconds = [[self.pickerData objectAtIndex:row] intValue];
}
}
#end
// SecondViewController
//.h
#import "ViewController.h"
#interface SecondViewController : ViewController
#property (nonatomic) int seconds;
#property (weak, nonatomic) IBOutlet UILabel *timeLabel;
#end
//.m
#import "SecondViewController.h"
#interface SecondViewController ()
#end
#implementation SecondViewController
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[NSTimer scheduledTimerWithTimeInterval:7 target:self selector:#selector(timeout)
userInfo:nil repeats:NO];
[NSTimer scheduledTimerWithTimeInterval:self.seconds target:self selector:#selector(setTimeToLabel) userInfo:nil repeats:NO];
}
-(void)timeout
{
// pops to root view
}
- (void)setTimeToLabel
{
self.seconds = self.seconds - 1;
self.timeLabel.text = [NSString stringWithFormat:#"%d", self.seconds];
}
#end
I am trying to set up a countdown timer. I have two view controllers: ViewController and EditViewController. ViewController has two labels hours and minutes. EditViewController has a UIDatePicker and a save button. When the user selects a time on the UIDatePicker and hits save, they are redirected back to the ViewController and the hour and minute labels are populated with the difference between the selected time and current time. This is automatically updated until the difference is 0. I have having issues trying to get the hour and minutes to display correctly on the ViewController labels. Here is my code:
ViewController.m
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.hourLabel.text = self.hourText;
self.minuteLabel.text = self.minuteText;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
EditViewController.h
#interface EditViewController : UIViewController
#property (weak, nonatomic) IBOutlet UIDatePicker *datePicker;
#property (weak, nonatomic) IBOutlet NSString *currentTimeString;
#property (weak, nonatomic) IBOutlet NSString *endTimeString;
- (IBAction)saveButton:(id)sender;
- (IBAction)cancelButton:(id)sender;
-(void)updateTime;
#end
EditViewController.m
#import "EditViewController.h"
#import "ViewController.h"
#interface EditViewController ()
#end
#implementation EditViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)saveButton:(id)sender
{
NSCalendar *now = [NSCalendar autoupdatingCurrentCalendar];
NSInteger currentTime = (NSHourCalendarUnit | NSSecondCalendarUnit);
self.datePicker.date = [now dateFromComponents:[now components:currentTime fromDate:self.datePicker.date]];
NSTimer *timer;
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(updateTime) userInfo:nil repeats:YES];
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)updateTime
{
NSInteger timeLeft = ((NSInteger)[self.datePicker.date timeIntervalSinceNow]);
NSInteger minutes = (timeLeft / 60) % 60;
NSInteger hours = (timeLeft / 3600) % 24;
ViewController *controller;
controller.hourText = [NSString stringWithFormat:#"%ldi",(long)hours];
controller.minuteText = [NSString stringWithFormat:#"%ldi",(long)minutes];
NSLog(#"The time is %ld",(long)timeLeft);
}
- (IBAction)cancelButton:(id)sender
{
[self dismissViewControllerAnimated:YES completion:nil];
}
#end
Any help is appreciated. Thanks in advance.
Have a look at here for the edited method from your code. This will full-fill your requirement.
#import "EditViewController.h"
#import "ViewController.h"
#import "AppDelegate.h"
#interface EditViewController ()
{
AppDelegate *appDelegate;
}
#end
#implementation EditViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
// Custom initialization
appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
}
return self;
}
-(void)updateTime
{
NSInteger timeLeft = ((NSInteger)[self.datePicker.date timeIntervalSinceNow]);
NSInteger minutes = (timeLeft / 60) % 60;
NSInteger hours = (timeLeft / 3600) % 24;
NSString *hourText = [NSString stringWithFormat:#"%ldi",(long)hours];
NSString *minuteText = [NSString stringWithFormat:#"%ldi",(long)minutes];
[appDelegate updateTime:hourText andMinute:minuteText];
}
and finally, define a method in AppDelegate class
- (void) updateTime:(NSString *)hourStr andMinute:(NSString *)minuteStr
{
for(id obj in [self.navigationController viewControllers])
{
if([obj isKindOfClass:ViewController])
{
ViewController *vcObj = (ViewController *)obj;
vcObj.hourLabel.text = hourStr;
vcObj.minuteLabel.text = minuteStr;
}
}
}
Several issues:
ViewController.m
self.hourLabel.text = self.hourText;
self.minuteLabel.text = self.minuteText;
Should be in viewWillAppear instead of viewDidLoad. What's happening is you set the text when the app loads. viewDidLoad will only fire once for that instance of the app ever. What you're needing to do is update it when you come back from the EditViewController, right? So if you put it in viewWillAppear, it will also get called when you come back and update it for you.
The next thing:
EditViewController.m
ViewController *controller;
controller.hourText = [NSString stringWithFormat:#"%ldi",(long)hours];
controller.minuteText = [NSString stringWithFormat:#"%ldi",(long)minutes];
NSLog(#"The time is %ld",(long)timeLeft);
This code snippet is declaring a new ViewController variable (well, most of it, you're missing the = [ViewController new] part). The problem with this is that you don't do anything with this controller. ViewController is actually already in your navigation stack (I'm assuming NavigationController since you said when the user goes back), so you need to use the reference to ViewController your app has already instantiated, not create a new one since you never use this guy anywhere.
My UIScrollView is not responding to touch events, nor is my touchesBegain method being called for my UIViewController. (Also the text on my buttons are distorted on one and not shown on the other)
In Storyboard I added the ScrollView to the UIViewController and added my UITextFields and UIButtons to the ScrollView
Here is the code:
#import <UIKit/UIKit.h>
#interface RefineSearchViewController : UIViewController <UITextFieldDelegate, UIScrollViewDelegate>
{
IBOutlet UIScrollView *scroller;
}
#property (strong, nonatomic) IBOutlet UITextField *nameField;
#property (strong, nonatomic) IBOutlet UITextField *targetField;
#property (strong, nonatomic) IBOutlet UITextField *vendorField;
#property (strong, nonatomic) IBOutlet UITextField *CATField;
#property (strong, nonatomic) IBOutlet UITextField *clonalityField;
#property (strong, nonatomic) IBOutlet UITextField *sourceOrganismField;
-(IBAction) textFieldReturn: (id) sender;
#import "RefineSearchViewController.h"
#import "DBHandler.h"
#interface RefineSearchViewController ()
#end
#implementation RefineSearchViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[scroller setScrollEnabled:YES];
// set the content size to be the size our our whole frame
//scroller.frame = CGRectMake(74, 261, 620, 354);
[scroller setContentSize:CGSizeMake(2000, 2000)];
[scroller setCanCancelContentTouches:NO];
[super viewDidLoad];
// Do any additional setup after loading the view.
self.targetField.delegate = self;
self.nameField.delegate = self;
self.vendorField.delegate = self;
self.clonalityField.delegate = self;
self.sourceOrganismField.delegate = self;
self.CATField.delegate = self;
}
-(void) viewWillAppear:(BOOL)animated
{
self.navigationController.navigationBarHidden = YES;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// If you are going to conduct a refine search
if ([[segue identifier] isEqualToString:#"Refine"])
{
DBHandler *handler = [[DBHandler alloc]init];
//Run searches on each of the parameter that aren't empty
NSString *nameParameter = _nameField.text;
if (![nameParameter isEqualToString:#""])
{
[handler search:0 andInput:nameParameter];
}
NSString *targetParameter = _targetField.text;
if(![targetParameter isEqualToString:#""])
{
[handler search:1 andInput:targetParameter];
}
NSString *vendorParameter = _vendorField.text;
if (![vendorParameter isEqualToString:#""])
{
[handler search:2 andInput:vendorParameter];
}
NSString *catParameter = _CATField.text;
if (![catParameter isEqualToString:#""])
{
[handler search:3 andInput:catParameter];
}
NSString *clonalityField = _clonalityField.text;
if (![catParameter isEqualToString:#""])
{
[handler search:4 andInput:clonalityField];
}
NSString *sourceField = _sourceOrganismField.text;
if (![sourceField isEqualToString:#""])
{
[handler search:5 andInput:sourceField];
}
//recursive implementation
for (int i = 0; i < 6 ; i++)
{
}
//We shouldn't clear the text fields here in my personal opinion because they apply to the search until you return to the homescreen and reset what is the
//current "working database"
}
//if you are going to cancel the refine search, simply go back to the previous screen
else if ([[segue identifier] isEqualToString:#"Cancel"])
{
//Do Nothing
//but more importantly....
//....clear Text Fields
_nameField.text = #"";
_targetField.text = #"";
_vendorField.text = #"";
_CATField.text = #"";
_clonalityField.text = #"";
_sourceOrganismField.text = #"";
}
}
//make that stubborn keyboard go away whenever you touch the background
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[_nameField resignFirstResponder];
[_targetField resignFirstResponder];
[_vendorField resignFirstResponder];
[_CATField resignFirstResponder];
[_clonalityField resignFirstResponder];
[_sourceOrganismField resignFirstResponder];
}
-(IBAction)textFieldReturn:(id)sender
{
[sender resignFirstResponder];
}
//following code was taken and tweaked from stack overflow
//- (void)textFieldDidBeginEditing:(UITextField *)textField
//{
// [self animateTextField: textField up: YES];
// NSLog(#"YO");
//}
//
//
//- (void)textFieldDidEndEditing:(UITextField *)textField
//{
// [self animateTextField: textField up: NO];
//}
//
//- (void) animateTextField: (UITextField*) textField up: (BOOL) up
//{
// const int movementDistance = 216; //height of the keyboard
// const float movementDuration = 0.3f; // duration of the animation
//
// int movement = (up ? -movementDistance : movementDistance);
//
// [UIView beginAnimations: #"anim" context: nil];
// [UIView setAnimationBeginsFromCurrentState: YES];
// [UIView setAnimationDuration: movementDuration];
// self.view.frame = CGRectOffset(self.view.frame, 0, movement);
// [UIView commitAnimations];
//}
#end
Make sure your scrollView's delegate is set properly in storyboard and scrollView's userInteractionEnabled is set.
my application has 3 views
in view1 only one button (play level 1) that pushes to veiw2 and updates titlelabel in view2
when view2 loads and appears a timer starts to count down and update another label in view2 itself, also view2 has button that pauses the timer and pushes to view3
in view3 only one button that pop back to view2 and resumes thee timer
my problem is that when i pop from view3 to view2 the timer is still paused
any help please?
Thanks & kind regards.
view1.h
#import <UIKit/UIKit.h>
#interface view1 : UIViewController
-(IBAction)nextpage;
#end
view1.m
#import "view1.h"
#import "view2.h"
#interface view1 ()
#end
#implementation view1
-(IBAction)nextpage{
view2 *obj = [[view2 alloc] init];
[self.navigationController pushViewController:obj animated:YES];
[obj.leveltitle setText:#"Level"];
obj.time=10;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[self.navigationController setNavigationBarHidden:YES];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
view2.h
#import <UIKit/UIKit.h>
#interface view2 : UIViewController
{
int time;
NSTimer *timer;
BOOL paused;
}
#property (nonatomic, retain) NSTimer *timer;
#property (readwrite, nonatomic) int time;
#property (nonatomic) BOOL paused;
#property (readwrite, retain) IBOutlet UILabel *leveltitle;
#property (nonatomic, readwrite) IBOutlet UILabel *label;
-(IBAction)back;
-(IBAction)pause;
#end
view2.m
#import "view2.h"
#import "view3.h"
#interface view2 ()
#end
#implementation view2
#synthesize leveltitle, label;
#synthesize time, timer;
#synthesize paused;
-(void)countDown2
{
if (paused == NO && time>0)
{
time = time -1 ;
view3 *obj = [[view3 alloc] init];
obj.sss = time;
if (time == 0)
{
[timer invalidate];
}
[label setText:[NSString stringWithFormat:#"%i",time]];
}
}
-(IBAction)back{
[self.navigationController popViewControllerAnimated:YES];
}
-(IBAction)pause{
view3 *obj = [[view3 alloc] init];
[self.navigationController pushViewController:obj animated:YES];
paused = YES;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
paused = NO;
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(countDown2) userInfo:nil repeats:YES];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
view3.h
#import <UIKit/UIKit.h>
#interface view3 : UIViewController
{
int sss;
}
#property (nonatomic) int sss;
-(IBAction)back;
#end
view3.m
#import "view3.h"
#import "view2.h"
#interface view3 ()
#end
#implementation view3
#synthesize sss;
-(IBAction)back{
view2 *obj = [[view2 alloc] init];
obj.paused=NO;
obj.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(cont) userInfo:nil repeats:YES];
//[obj.timer fire];
[self.navigationController popViewControllerAnimated:YES];
}
-(void)cont{
view2 *obj = [[view2 alloc] init];
obj.time = sss;
if (obj.paused == NO && time>0)
{
obj.time = obj.time -1 ;
if (obj.time == 0)
{
[obj.timer invalidate];
}
[obj.label setText:[NSString stringWithFormat:#"%i",obj.time]];
}
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
It is because in view3's back method, you created a new instant of view2 name obj and set paused=NO. But that obj was not the same instant of view2 when you pop back. What you need to do is to use a delegate method pattern, so that view3 will have a callback method in view2 to set the paused to NO.
For an example of delegate method pattern, check out an example from this SO.
Edit: sample callback code:
Make these addition/changes to your code:
In view2.h:
#import "view3.h"
#interface view2 : UIViewController <view3Delegate>
In view2.m:
-(IBAction)pause{
view3 *obj = [[view3 alloc] init];
obj.delegate = self; //adding this line
[self.navigationController pushViewController:obj animated:YES];
paused = YES;
}
-(void)setPausedValue:(BOOL)value //this is the new method callback from view3 to set paused value
{
paused = value;
}
In view3.h:
#import <UIKit/UIKit.h>
#protocol view3Delegate <NSObject>
-(void) setPausedValue:(BOOL)value;
#end
#interface view3 : UIViewController
{
int sss;
}
#property (assign) id <view3Delegate> delegate;
#property (nonatomic) int sss;
-(IBAction)back;
#end
In view3.m:
#implementation view3
#synthesize delegate;
-(IBAction)back{
// view2 *obj = [[view2 alloc] init];
// obj.paused=NO;
[self.delegate setPausedValue:NO]; //make callback and set value
obj.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(cont) userInfo:nil repeats:YES];
//[obj.timer fire];
[self.navigationController popViewControllerAnimated:YES];
}