how to resume timer when poping to view2 - ios

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

Related

Why the String value is null?

Why the string value is getting null value. Someone please find the error?
How can i fetch the string value when the method is getting called from SecondViewController do i need a another string or someone please suggest some corrections.
I need this string to be have some value
#property (nonatomic,strong) NSString *str;
When the following method is getting called.
[view getTotal];
Label is in the first view controller.
Thanks in advance.
In ViewController.m
#import "ViewController.h"
#import "SecondViewController.h"
#interface ViewController ()
{
NSInteger total;
}
#property (weak, nonatomic) IBOutlet UILabel *lbl;
#property (weak, nonatomic) IBOutlet UIButton *btn;
#property (nonatomic,strong) NSString *str;
- (id)initWithInitialNumber:(NSInteger)initialNumber;
- (void)addNumber:(NSInteger)newNumber;
- (NSInteger)getTotal;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"%#",_str);
self.lbl.text = _str;
// Do any additional setup after loading the view, typically from a nib.
}
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
NSLog(#"viewDidAppear called");
[self viewDidLoad];
}
-(id)initWithInitialNumber:(NSInteger)initialNumber{
total = initialNumber;
return self;
}
-(void)addNumber:(NSInteger)newNumber{
total += newNumber;
}
-(NSInteger)getTotal{
NSLog(#"Number is: %ld",total);
self.str = [NSString stringWithFormat:#"%ld",total];
NSLog(#"%#",self.str);
return total;
}
- (IBAction)btnAct:(id)sender {
UIStoryboard *sb = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
SecondViewController *SC = [sb instantiateViewControllerWithIdentifier:#"SC"];
[self presentViewController:SC animated:YES completion:nil];
}
-(NSString *)str{
return _str;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
In SecondViewController.m
#import "SecondViewController.h"
#import "ViewController.h"
#interface SecondViewController ()<Sendata>
{
NSInteger *num;
}
#end
#implementation SecondViewController
- (IBAction)backBtn:(id)sender {
ViewController *VC = [self.storyboard instantiateViewControllerWithIdentifier:#"VC"];
[self presentViewController:VC animated:YES completion:nil];
}
- (void)viewDidLoad {
[super viewDidLoad];
ViewController *view = [[ViewController alloc]initWithInitialNumber:10];
view.delegate = self;
[self Print:#"Hello"];
[view addNumber:2];
[view getTotal];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)Print:(NSString *)str{
NSLog(#"%#",str);
}
#end
What I can understand from your code is that you are presenting secondViewController from ViewController on a button click. On Second view controller you want to add two numbers and show them on Firstview controller again.
what I can see from your code , you are pushing the new instance of ViewController every time. So thevalue you are intialising in your view didLoad in diffrent object then the one your pushing again on button action of back. IF you can modify you code like this , it will work :
#interface ViewController ()
{
NSInteger total;
}
#property (weak, nonatomic) IBOutlet UILabel *lbl;
#property (weak, nonatomic) IBOutlet UIButton *btn;
#property (nonatomic,strong) NSString *str;
- (id)initWithInitialNumber:(NSInteger)initialNumber;
- (void)addNumber:(NSInteger)newNumber;
- (NSInteger)getTotal;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"%#",_str);
self.lbl.text = _str;
// Do any additional setup after loading the view, typically from a nib.
}
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
NSLog(#"viewDidAppear called");
[self viewDidLoad];
}
-(id)initWithInitialNumber:(NSInteger)initialNumber{
total = initialNumber;
return self;
}
-(void)addNumber:(NSInteger)newNumber{
total += newNumber;
}
-(NSInteger)getTotal{
NSLog(#"Number is: %ld",total);
self.str = [NSString stringWithFormat:#"%ld",total];
NSLog(#"%#",self.str);
return total;
}
- (IBAction)btnAct:(id)sender {
UIStoryboard *sb = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
SecondViewController *SC = [sb instantiateViewControllerWithIdentifier:#"SC"];
[self.navigationController pushViewController:SC animated:YES];
}
-(NSString *)str{
return _str;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
#interface SecondViewController ()
{
NSInteger *num;
ViewController *viewController;
}
#end
#implementation SecondViewController
- (IBAction)backBtn:(id)sender {
[self.navigationController popViewControllerAnimated:YES]
}
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableArray *VCs = [NSMutableArray arrayWithArray: self.navigationController.viewControllers];
if ([[VCs objectAtIndex:[VCs count] - 2] isKindOfClass:[ViewController class]])
{
ViewController *view = [[VCs objectAtIndex:[VCs count] - 2]
view.delegate = self;
[self Print:#"Hello"];
[view addNumber:2];
[view getTotal];
}
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)Print:(NSString *)str{
NSLog(#"%#",str);
}
#end
I have taken the instance of ViewController already present in navigation stack , changed the values and on back I have pop out the SecondViewController.

failure of alloc and Init

So perhaps this is a beginner's mistake and super easy to you guys, but i really do not know how to solve it,really appreciate for any suggestions:
Right Now:
1: I have to ViewController: EnterCommandViewController and DetectionViewController
2: I wrote Delegate protocol in EnterCommandViewController and set DetectionViewController as its delegate.
3: About delegate: I have a inputTextField in the EnterCommandView and a "Save" bar button item on the top toolbar in this view. Once I click the save , current view will be dismissed and return back to DetectionView and show the NSString just entered in the UILabel in DetectionView.
Finally, My question is that Why After I alloc and init a EnterCommandViewController instance , that is enterCVS, the instance is still nil as show in end of my post.
Code:
EnterCommandViewController.h
#import <UIKit/UIKit.h>
#import "RscMgr.h"
#protocol EnterCommandDelegate <NSObject>
#optional
-(void) commandEntered:(NSString*)command;
#end
#interface EnterCommandViewController : UIViewController <RscMgrDelegate,EnterCommandDelegate>
{
RscMgr* rscMgr;
IBOutlet UITextField *inputTextField;
// DetectionViewController* detectionViewController;
// __unsafe_unretained id<EnterCommandDelegate> delegate;
}
-(void)sendMessage:(NSString*)message;
-(id)initWithDelegate:(id)delegateToBe;
- (IBAction)cancelPressed;
- (IBAction)savePressed;
#property (nonatomic,weak) id<EnterCommandDelegate> delegate; //assign replaced
#end
EnterCommandVIewController.m
#import "EnterCommandViewController.h"
#import "DetectionViewController.h"
#interface EnterCommandViewController () <UITextFieldDelegate>
{
#private
BOOL connected;
}
#end
#implementation EnterCommandViewController
#synthesize delegate;
- (void)viewDidLoad {
[super viewDidLoad];
rscMgr = [[RscMgr alloc] init];
[rscMgr setDelegate:self];
// Do any additional setup after loading the view, typically from a nib.
[inputTextField becomeFirstResponder];
}
-(id)initWithDelegate:(id)delegateToBe{
if(self = [super init]){
delegate = delegateToBe;
}
return self;
}
-(void) viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
inputTextField.delegate = self;
}
-(void) viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
inputTextField.delegate = nil;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - UITextFieldDelegate Methods
-(BOOL) textFieldShouldReturn:(UITextField *)textField{
[self sendMessage:textField.text];
textField.text = nil;
return NO;
}
#pragma mark - Serial Tx/Rx Methods Implementation
-(void) sendMessage:(NSString *)message{
if(connected == YES) {
[rscMgr writeString:message];
}
else{
NSLog(#"CableDisconnected!");
NSLog(#"Attempted To Send: %#",message);
}
}
- (IBAction)cancelPressed {
[self dismissViewControllerAnimated:YES completion:^{}];
}
- (IBAction)savePressed {
//is anyone listening
if([[[UIDevice currentDevice]systemVersion] compare:#"7.0" options:NSNumericSearch] != NSOrderedAscending){
NSLog(#"SYStem version > 7.0");
}
if(delegate&&[delegate respondsToSelector:#selector(commandEntered:)]){
NSLog(#"SomeMethod is listening");
[delegate commandEntered:inputTextField.text];
}
[self dismissViewControllerAnimated:YES completion:nil]; //commened: ^{}
}
#pragma mark - RscMgrDelegate Methods Implementation
-(void) cableConnected:(NSString *)protocol{
inputTextField.text = #"cableConnected";
[rscMgr setBaud:9600];
[rscMgr open];
connected = YES;
}
-(void) cableDisconnected{
inputTextField.text = #"cableDisconnected";
connected = NO;
}
-(void) readBytesAvailable:(UInt32)length{}
-(void) portStatusChanged{}
#end
DetectionViewController.h
#import <UIKit/UIKit.h>
#import "EnterCommandViewController.h"
#interface DetectionViewController : UIViewController <EnterCommandDelegate>{
}
- (IBAction)showSettings:(UIBarButtonItem *)sender;
#property (nonatomic, strong) EnterCommandViewController* enterCVC;
#property (nonatomic, strong) IBOutlet UILabel *showReceivedCommand;
#end
DetectionViewController.m
#import <Foundation/Foundation.h>
#import "DetectionViewController.h"
#import "EnterCommandViewController.h"
#implementation DetectionViewController
#synthesize showReceivedCommand;
#synthesize enterCVC;
- (IBAction)showSettings:(UIBarButtonItem *)sender {
}
-(void) viewDidLoad{
[super viewDidLoad];
if(showReceivedCommand){
showReceivedCommand.text=#"Initial text";
NSLog(#"UILAbel in ViewDidload is not nil");
}else {
NSLog(#"UILAbel in viewDidload is nil");
}
enterCVC = [[EnterCommandViewController alloc] init];
if(enterCVC.delegate) NSLog(#"X nil");
[enterCVC setDelegate:self];
}
#pragma mark - EnterCommandDelegate function(s)
-(void)commandEntered:(NSString *)command{
dispatch_async(dispatch_get_main_queue(), ^{
if(showReceivedCommand){
NSLog(#"UILabel is not nil");
}else{NSLog(#"UILabel is nil");}
showReceivedCommand = [[UILabel alloc] init];
NSLog(#"command received: %#",command);
showReceivedCommand.text = command;
[showReceivedCommand setNeedsDisplay];
NSLog(#"text in showReceivedCommand is %#",showReceivedCommand.text);
});
}
#end
I set a break point at DetectionViewController.n --> ViewDidLoad() --> [enterCVC setDelegate:self];
I got:
self DetectionViewController * 0x15c50e850 0x000000015c50e850
UIViewController UIViewController
showReceivedCommand UILabel * 0x15c510650 0x000000015c510650
enterCVC EnterCommandViewController * 0x15c611360 0x000000015c611360
showReceivedCommand UILabel * 0x15c510650 0x000000015c510650
enterCVC EnterCommandViewController * 0x15c611360 0x000000015c611360
UIViewController UIViewController
rscMgr RscMgr * nil 0x0000000000000000
inputTextField UITextField * nil 0x0000000000000000
connected BOOL NO false
delegate id 0x0 0x0000000000000000
enterCVC = [[EnterCommandViewController alloc] init]
Try changing that to....
enterCVC = [[EnterCommandViewController alloc] initWithDelegate:self];

Countdown timer: updating controller view labels

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.

Can't change label.text and don't know why

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

Can't connect IBAction to view

I'm new to iOS and I'm following this tutorial.
Here is a screenshot of me trying to connect an IBAction to my view.
I want to execute the method releaseKeyboard whenever I touch the view (ie. close the keyboard).
I'm not using storyboard.
My files:
challAppDelegate.h
challAppDelegate.m
challViewController.h
challViewController.m
challViewController.xib
challAppDelegate.h
#import <UIKit/UIKit.h>
#interface challAppDelegate : UIResponder <UIApplicationDelegate>
{
UINavigationController *navigationController;
}
#property (strong, nonatomic) UIWindow *window;
#property (strong, nonatomic) UINavigationController *navigationController;
#end
challAppDelegate.m
#import "challAppDelegate.h"
#import "challViewController.h"
#implementation challAppDelegate
#synthesize window = _window;
#synthesize navigationController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
UIViewController *rootController =
[[challViewController alloc]
initWithNibName:#"challViewController" bundle:nil];
navigationController = [[UINavigationController alloc]
initWithRootViewController:rootController];
self.window = [[UIWindow alloc]
initWithFrame:[[UIScreen mainScreen] bounds]];
[self.window addSubview:navigationController.view];
[self.window makeKeyAndVisible];
return YES;
}
...
...
challViewController.h
#import <UIKit/UIKit.h>
#interface challViewController : UIViewController
#property(nonatomic, retain) IBOutlet UITextField *signInEmailAddress;
#property(nonatomic, retain) IBOutlet UITextField *signInPassword;
#property(nonatomic, retain) IBOutlet UIButton *signInSignInButton;
#property(nonatomic, retain) IBOutlet UIButton *signInRegisterButton;
-(void) releaseKeyboardAction;
-(IBAction) signInAction:(int)sender;
-(IBAction) registerAction:(int)sender;
-(IBAction) releaseKeyboard:(id)sender;
#end
challViewController.m
#import "challViewController.h"
#interface challViewController ()
#end
#implementation challViewController
#synthesize signInEmailAddress; // cria os getters e setters
#synthesize signInPassword; // cria os getters e setters
#synthesize signInSignInButton; // cria os getters e setters
#synthesize signInRegisterButton; // cria os getters e setters
- (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.
self.title = #"Sign In";
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)releaseKeyboardAction
{
[signInEmailAddress resignFirstResponder];
[signInPassword resignFirstResponder];
}
- (IBAction)releaseKeyboard:(id)sender
{
[self releaseKeyboardAction];
}
- (IBAction)registerAction:(int)sender
{
//
}
- (IBAction)signInAction:(int)sender
{
//
}
#end
What am I doing wrong?
Thanks
You can add a UITapGestureRecognizer to self.view.
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
self.title = #"Sign In";
UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(releaseKeyboardAction)];
[self.view addGestureRecognizer:gesture];
}
The target of the gesture recogniser points to your releaseKeyboardAction method.
Just change the view's class from UIView to UIControl in the identity inspector and then you can connect IBActions.

Resources