Merged with How to change label in ViewController when app enters the foreground.
i want to change a label in my view controller when the app enters the foreground....:
SalaryAppV4AppDelegate.h
#interface SalaryAppV4AppDelegate : NSObject {
//----------------------------------------------
NSTimeInterval appEnteredBackground;
NSTimeInterval appEnteredForeground;
NSTimeInterval difference;
NSString *times;
//-----------------------------------------------
SalaryAppV4AppDelegate.m
(void)applicationWillEnterForeground:(UIApplication *)application
{
//perform -(IBAction)DoThis
FirstViewController* controller = [FirstViewController alloc];
[controller DoThis];
//releasing
[dateFormatter release];
}
//---------------------------------------------------------------------
FirstViewController.h
import UIKit/UIKit.h>
import "SalaryAppV4AppDelegate.h"
#interface FirstViewController : UIViewController {
IBOutlet UITextField *text1;
IBOutlet UILabel *label;
IBOutlet UILabel *labeltotal;
IBOutlet UILabel *differenceLabel;
int i;
float number1;
NSTimer *timer;
SalaryAppV4AppDelegate *appDelegate;
}
//Actions
-(IBAction)reset:(id)sender;
-(IBAction)backgroundTouched:(id)sender;
-(IBAction) beginTimer;
-(void) DoThis;
//Properties
#end
//--------------------------------------------------------------------
FirstViewController.m
-(IBAction) DoThis
{
appDelegate = [[[UIApplication sharedApplication] delegate] retain];
//This Doesn't Work :(
label.text = #"IT Has Worked";
//This Works
NSLog(#"%#", appDelegate.times);
}
//--------------------------------------------------------
i just want the label.text ti change to anything but nothing in the viewcontroller changes...
Related
I am trying to make my own delegate method for this I declare 'Mydelegate' protocol in forDelegate.h file.
#protocol Mydelegate <NSObject>
-(void)show:(NSString *)msg;
#end
then in my first viewController I make the property for this.I declare a method clickMe which is call on button press,that button is present in my firstviewcontroller .xib file.
#class SecondViewController;
#interface ViewController : UIViewController
{
id <Mydelegate> delegate1;
SecondViewController *secondController;
}
#property (assign) id <Mydelegate> delegate1;
-(IBAction)clickMe:(id)sender;
#end
and then after I adopt this protocol in my second view controller and define the method of this protocol
SecondViewController.h file
#class ViewController;
#interface SecondViewController : UIViewController <Mydelegate>
{
ViewController *viewController;
}
SecondViewController.m file
-(void)show:(NSString *)msg
{
NSLog(#"in delegate mathod");
}
-(void)viewDidLoad
{
viewController =[[ViewController alloc] initWithNibName:#"ViewController" bundle:nil];
viewController.delegate1=self;
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
Program is running but Mydelegate method 'show' is not call.
This will be a useful answer for your question.
In the implementation of ViewController, you should call the delegate's method..
-(IBAction)clickMe:(id)sender
{
[self.delegate1 show:#"Your String Param"];
}
Create one button on second view controller xib and connect method to that button then after click that button check your console.
#class ViewController;
#interface SecondViewController : UIViewController <Mydelegate>
{
ViewController *viewController;
}
-(IBAction)showmsg;
SecondViewController.m file
-(void)show:(NSString *)msg
{
NSLog(#"in delegate mathod");
}
-(IBAction)showmsg
{
[self show:];
}
-(void)viewDidLoad
{
viewController =[[ViewController alloc] initWithNibName:#"ViewController" bundle:nil];
viewController.delegate1=self;
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
#protocol CPUPerformanceDelegate <NSObject>
-(void)getUsedCpuOperations:(float)percent;
-(void)getKernelCpuOperations:(float)percent;
-(void)getIdleCpuOperations:(float)percent;
-(void)getUserCpuOperations:(float)percent;
-(void)getNiceCpuOperations:(float)percent;
#end
#interface CPUPerformance : NSObject{
processor_info_array_t cpuInfo, prevCpuInfo;
mach_msg_type_number_t numCpuInfo, numPrevCpuInfo;
unsigned numCPUs;
NSLock *CPUUsageLock;
}
#property(nonatomic,assign)id<CPUPerformanceDelegate>delegate;
#property(nonatomic,retain)NSTimer *updateTimer;
#end
Then
#import "CPUPerformance.h"
#implementation CPUPerformance
#synthesize delegate,updateTimer;
- (void)updateInfo
{
idlepercent = ((idle/total)*100);
userpercent = (user/total)*100;
syspercent = (sys/total)*100;
nicepercent = (nice/total)*100;
inUsepercent = (inUse/total)*100;
[delegate getIdleCpuOperations:idlepercent];
[delegate getKernelCpuOperations:syspercent];
[delegate getNiceCpuOperations:nicepercent];
[delegate getUsedCpuOperations:inUsepercent];
[delegate getUserCpuOperations:userpercent];
}
and finally
#import "CPUPerformance.h"
#interface SpecProjectFirstViewController : UIViewController<UITableViewDataSource,UITableViewDelegate,CPUPerformanceDelegate>{
//Ivars
NSMutableArray *processArray;
//User Interface Object
UILabel *cpuUsage;
UILabel *cpuIdle;
UILabel *cpuUser;
UILabel *cpuNice;
UILabel *cpuKernel;
IBOutlet UITableView *tableViews;
CPUPerformance *cpuObject;
}
=================
#import "SpecProjectFirstViewController.h"
#implementation SpecProjectFirstViewController
-(void)getIdleCpuOperations:(float)percent{
[cpuIdle setText:nil];
[cpuIdle setText:[NSString stringWithFormat:#"Idle :%.0f %%",percent]];
[cpuIdle setTextAlignment:UITextAlignmentCenter];
}
-(void)getKernelCpuOperations:(float)percent{
[cpuKernel setText:nil];
[cpuKernel setText:[NSString stringWithFormat:#"Kernel :%.0f %%",percent]];
[cpuKernel setTextAlignment:UITextAlignmentCenter];
}
-(void)getNiceCpuOperations:(float)percent{
[cpuNice setText:nil];
[cpuNice setText:[NSString stringWithFormat:#"Nice :%.0f %%",percent]];
[cpuNice setTextAlignment:UITextAlignmentCenter];
}
-(void)getUsedCpuOperations:(float)percent{
[cpuUsage setText:nil];
[cpuUsage setText:[NSString stringWithFormat:#"Used :%.0f %%",percent]];
[cpuUsage setTextAlignment:UITextAlignmentCenter];
}
-(void)getUserCpuOperations:(float)percent{
[cpuUser setText:nil];
[cpuUser setText:[NSString stringWithFormat:#"User :%.0f %%",percent]];
[cpuUser setTextAlignment:UITextAlignmentCenter];
}
-(void)viewDidAppear:(BOOL)animated{
cpuObject = [[CPUPerformance alloc]init];
cpuObject.delegate = self;
[self creatObjectsOnView];
[super viewDidAppear:animated];
}
In my application I have a UISlider where file.h is:
#interface Mapa : UIViewController {
UILabel *label;
UISlider *slider;
}
#property(nonatomic, retain) IBOutlet UILabel *label;
#property(nonatomic, retain) IBOutlet UISlider *slider;
-(IBAction)sliderValueChanged:(UISlider *)sender;
-(IBAction) OpenList:(id)sender;
-(IBAction) OpenMap:(id)sender;
And file.m:
#synthesize label;
#synthesize slider;
-(IBAction)sliderValueChanged:(UISlider *)sender {
label.text = [NSString stringWithFormat:#"%f", sender.value];
}
- (void)dealloc {
[super dealloc];
[label release];
[slider release];
}
done this to me uislider goal of the label, I get the number that's out on the label bound to the UISlider, another screen to call a map, how this value label step to the other screen?
thanks
Assuming your 'other screen' is another UIViewController, then after instantiating the new UIViewController, you would set the parameters on the new UIViewController before calling either pushViewController or presentModalViewController.
If you're using a UIStoryboard then you can set the parameters of the new view controller in 'prepareForSegue'. See this question How to pass prepareForSegue: an object for details.
I know this question as been asked over and over but it's still quite obscure to me, so I guess making an example with my code instead will probably be easier .
I know that you can use :
A global variable, ( not good practice ).
Use a delegate
Use a singleton
Say I've got this piece of code here in my first view controller header :
#import <UIKit/UIKit.h>
#interface FirstViewController : UIViewController {
IBOutlet UITextField *Te;
NSInteger evTe;
}
#property (nonatomic, retain) UITextField *Te;
#property (nonatomic) NSInteger evTe;
- (IBAction) makeKeyboardGoAway;
#end
and then this in my implementation file
#import "FirstViewController.h"
#implementation FirstViewController
#synthesize Te;
- (IBAction) makeKeyboardGoAway;
{
[Te resignFirstResponder];
evTe = [Te.text intValue];
}
How would I call evTe in my SecondViewController ? ( maybe using a delegate ?) .
This is what I've got in the second view Controller, header :
#interface SecondViewController : UIViewController {
NSInteger evTe;
}
#property (nonatomic) NSInteger evTe;
and implementation :
- (IBAction) makeKeyboardGoAway;
{
FirstViewController *first = [[FirstViewController alloc] init];
first.evTe = self.evTe;
NSLog(#"second value is %i",evTe);
}
Thanks a lot !
Edit for Tob
FirstViewController.m
- (IBAction) makeKeyboardGoAway;
{
evTe = [Te.text intValue];
NSLog(#"The value of integer num is %i", evTe);
NSDictionary *changedValues = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:evTe] forKey:#"evTe"];
[[NSNotificationCenter defaultCenter] postNotificationName:#"evTeChanged" object:self userInfo:changedValues];
}
SecondViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(methodToCall:) name:#"evTeChanged" object:nil];
}
- (void)methodToCall:(NSNotification *)aNotification{
NSDictionary *changedValues = [[aNotification userInfo] objectForKey:#"evTe"];
NSString *dictionaryString = [changedValues description];
NSLog(#"Notification returning %d",dictionaryString);
}
Unfortunately I'm not getting any log from the SecondView ..
By creating a #property called evTe or whatever in both view controllers.
If the FirstViewController is responsible for creating the SecondViewController you could store the value of evTe in a property in FirstViewController and then after you have created the SecondViewController you set the evTe property there as well.
- (IBAction) makeKeyboardGoAway;
{
[Te resignFirstResponder];
self.evTe = [Te.text integerValue];
}
// other method where SecondViewController is created
SecondViewController* second = [[SecondViewController alloc] init];
second.evTe = self.evTe;
// do what ever
--Edit--
#interface FirstViewController : UIViewController {
IBOutlet UITextField *Te;
NSInteger evTe;
}
#property (nonatomic, retain) UITextField *Te;
#property (nonatomic) NSInteger evTe;
Have a look at NSNotification. You should send a notification that the particular value has changed and register for that notification in the second view controller.
- (IBAction) makeKeyboardGoAway;
{
[Te resignFirstResponder];
evTe = [Te.text intValue];
NSDictionary *changedValues = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:evTe] forKey:#"evTe"];
[[NSNotificationCenter defaultCenter] postNotificationName:#"evTeChanged" object:self userInfo:changedValues];
}
And in the viewDidLoad method of the other controller do:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(methodToCall:) name:#"evTeChanged" object:nil];
Now every time the first controller calls makeKeyboardGoAway the method - (void)methodToCall:(NSNotification *)aNotification will be called.
Implement this method and ask the aNotification for its userInfo which is the NSDictionary you created in the first controller before posting the notification. Get the evTe value out of it and do whatever you want to do with that value.
i have 2 views
i m sending text in a button on 1st view to label on second view....
//////textfieldtolabelViewController.h
#import <UIKit/UIKit.h>
#import "seconview.h"
#interface textfieldtolabelViewController : UIViewController {
IBOutlet seconview *sec;
//IBOutlet UITextField *t1;
}
//#property(nonatomic, retain)IBOutlet UITextField *t1;
-(void)buttonclick:(id)sender;
#end
and its .m file is this
#import "textfieldtolabelViewController.h"
#implementation textfieldtolabelViewController
-(void)buttonclick:(id)sender
{
NSString *s = [sender titleForState:UIControlStateNormal];
//sec.ss = s;
[sec settext:s];
[self presentModalViewController:sec animated:YES];
}
- (void)dealloc {
[super dealloc];
}
#end
now there is second view naming seconview
.h file
#import <UIKit/UIKit.h>
#interface seconview : UIViewController {
IBOutlet UILabel *l1;
}
#property(nonatomic, retain)IBOutlet UILabel *l1;
-(void)settext:(NSString *)ss;
#end
and its .m file is ....
#import "seconview.h"
#implementation seconview
#synthesize l1;
//#synthesize ss;
-(void)settext:(NSString *)ss
{
l1.text=ss;
}
- (void)dealloc {
[super dealloc];
}
#end
this program did not show any error and runs fine but problem is that the text of button in 1st view does not appear in label on second view
but i made all connection perfectly.......
Most probably you didn't connect l1 to the actual label in the Interface Builder. Verify with the debugger, that l1 is not nil in your settext method
You can include the view controller containing the label in the view controller where you want it to change, and access it by allocating a copy of it.
For example, use something like this in textfieldtolabelViewController.m
#import "seconview.h"
-(void)buttonclick:(id)sender
{
NSString *s = [sender titleForState:UIControlStateNormal];
seconview *viewcontroller = [[seconview alloc] initWithNibName:#"seconview" bundle:nil];
[[viewcontroller l1] setText:s];
[viewcontroller release];
[self presentModalViewController:sec animated:YES];
}
the [self presentModalViewController:sec animated:YES]; should be above the setText
try it
-(void)buttonclick:(id)sender
{
NSString *s = [sender titleForState:UIControlStateNormal];
//sec.ss = s;
[self presentModalViewController:sec animated:YES];
[sec settext:s];
}
hope it will work....
I have a login controller ,and after the successful login i want to pass some string value to the menu page.however it does not work.the application crashes.
I have tried possible suggesstion of Ihuk and SAM from the link below
how to pass a string value from one view controller to another view controller
loginController.h:
#import <UIKit/UIKit.h>
#class RootViewController;
#class Menu;
#interface LoginController : UIViewController {
UIButton *login_Button;
UITextField *username_TextField;
UITextField *password_TextField;
RootViewController *mc1;
UINavigationController *navigationController;
Menu *mv1;
}
#property(nonatomic,retain) IBOutlet UIButton *login_Button;
#property(nonatomic,retain) IBOutlet UITextField *username_TextField;
#property(nonatomic,retain) IBOutlet UITextField *password_TextField;
#property(nonatomic,retain) RootViewController *mc1;
#property (nonatomic, retain) IBOutlet
UINavigationController *navigationController;
#property(nonatomic,retain)Menu *mv1;
- (IBAction)Login_Method:(id)sender;
-(id)initWithUserName:(NSString *)name ;
#end
loginController.m
#import "LoginController.h"
#import "Menu.h"
#import "ViewController.h"
#import "RootViewController.h"
#implementation LoginController
#synthesize mc1,mv1;
#synthesize login_Button,username_TextField,password_TextField;
#synthesize navigationController;
// Implement viewDidLoad to do additional setup after
// loading the view, typically from a nib.
- (void)viewDidLoad {
if (![self.navigationController isNavigationBarHidden])
[self.navigationController setNavigationBarHidden:YES animated:NO];
//[self presentModalViewController:navigationController animated:YES];
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (IBAction)Login_Method:(id)sender
{
Menu *mv2 = [[Menu alloc] initWithUserName:#"Menu" bundle:nil];
//mv2.l1.text=#"aa"; //i tried this, but not work,so created initWithUserName
self.mv1=mv2;
[self presentModalViewController:mv1 animated:YES];
// [RootViewController release];
}
-(id)initWithUserName:(NSString *)name
{
self = [super init];
if (nil == self) {
return nil;
}
// display or store login info somewhere
[mv1.l1 setText:name];
return self;
}
-(BOOL)textFieldShouldReturn:(UITextField *)theTextField {
[theTextField resignFirstResponder];
return YES;
}
- (void)dealloc {
[username_TextField release];
[password_TextField release];
[super dealloc];
}
#end
Menu.h
#import <UIKit/UIKit.h>
#class Menu;
#interface Menu : UIViewController {
UILabel *l1;
UIButton *AccountSummary_Button;
UIButton *PayOffQuote_Button;
UIButton *PayBill_Button;
UIButton *Logout_Button;
UINavigationController *nv1;
}
#property(nonatomic,retain) IBOutlet UILabel *l1;
#property(nonatomic,retain) IBOutlet UIButton *AccountSummary_Button;
#property(nonatomic,retain) IBOutlet UIButton *PayOffQuote_Button;
#property(nonatomic,retain) IBOutlet UIButton *PayBill_Button;
#property(nonatomic,retain) IBOutlet UIButton *Logout_Button;
#property (nonatomic, retain) IBOutlet UINavigationController *nv1;
-(IBAction)ViewAccountSummary_method:(id)sender;
-(IBAction)ViewPayOffQuote_method:(id)sender;
-(IBAction)ViewPayBill_method:(id)sender;
-(IBAction)Logout_method:(id)sender;
#end
Menu.m
Make a property in your application delegate, for example, an NSString* called myString.
Then access it from the login controller and other controllers like so:
[[UIApplication sharedApplication] delegate].myString
You could, for example, set myString's value in the login controller:
[[UIApplication sharedApplication] delegate].myString = #"value";
You could read it in any other controller:
NSLog(#"myString is: %#", [[UIApplication sharedApplication] delegate].myString);
Additionally, some Cocoa style tips:
Do not capitalize class members (AccountSummary_Button etc.)
Do not capitalize class methods (ViewAccountSummary_method etc.)
The only thing you should capitalize are the classes themselves (Menu etc.).