So this a beginner's question, I have to admit, to you guys, but I really have no idea what I should do ,and it have taken me several hrs to try to fix it.
So: My question is that why the UILabel is nil when I want to update its text?
Details:
1:I have two Views and DetectionView is the initial View where there is a UILabel and a bar button item named "Setting" in the toolbat at the button of this view, and second View is the EnterCommandView where there is a UITextField and a bar button item named "save" in the toolbar at the top of this view.
2: After I enter a String, After the app finish launching, I click Setting, then I segue form first View to second View. In second, I enter some string in the UITextField and then click "Save" button, the second View is dismissed, and then I go back to the Initial View,
3: When I go back to the InitialView, the String just entered should appear in the UILabel, but , right it does not, which is exactly my problem, And then I set a breakpoint at the place where I update the UILabel, I have the info at the end of this post, saying UILabel is nil
Code:
EnterCommnadViewController.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;
}
-(void)sendMessage:(NSString*)message;
-(id)initWithDelegate:(id)delegateToBe;
- (IBAction)cancelPressed;
- (IBAction)savePressed;
#property (nonatomic,weak) id<EnterCommandDelegate> delegate;
#end
EnterCommandViewController.m
#import "EnterCommandViewController.h"
#import "DetectionViewController.h"
#interface EnterCommandViewController () <UITextFieldDelegate>
{
#private
BOOL connected;
}
#end
#implementation EnterCommandViewController
#synthesize delegate;
- (void)viewDidLoad {
[super viewDidLoad];
[inputTextField becomeFirstResponder];
}
-(void) viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
inputTextField.delegate = self;
}
-(void) viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
inputTextField.delegate = nil;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (IBAction)cancelPressed {
[self dismissViewControllerAnimated:YES completion:^{}];
}
- (IBAction)savePressed {
if([[[UIDevice currentDevice]systemVersion] compare:#"7.0" options:NSNumericSearch] != NSOrderedAscending){
NSLog(#"SYStem version > 7.0");
}
if(delegate&&[delegate respondsToSelector:#selector(commandEntered:)]){
[delegate commandEntered:inputTextField.text];
}
[self dismissViewControllerAnimated:YES completion:nil]; //commened: ^{}
}
#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"
#implementation DetectionViewController
#synthesize showReceivedCommand;
#synthesize enterCVC;
- (IBAction)showSettings:(UIBarButtonItem *)sender {
}
-(void) viewDidLoad{
[super viewDidLoad];
}
#pragma mark - EnterCommandDelegate function(s)
-(void)commandEntered:(NSString *)command{
dispatch_async(dispatch_get_main_queue(), ^{
showReceivedCommand.text = command;
});
}
#pragma mark -sugue
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
enterCVC = (EnterCommandViewController*)segue.destinationViewController;
[enterCVC setDelegate:self];
}
#end
Below is what I got when I set a breakPoint AT DetectionViewController.m --> -(void)commmandEntered:(NSString*)command{} --> showReceivedCommand.text = command;
self DetectionViewController * 0x1465132a0 0x00000001465132a0
command NSString * #"testStringJustEntered" 0x000000017424ada0
showReceivedCommand UILabel * 0x1465149d0 0x00000001465149d0
UIView UIView
UIResponder UIResponder
_layer CALayer * 0x17409ae50 0x000000017409ae50
_gestureInfo id 0x0 0x0000000000000000
_gestureRecognizers NSMutableArray * nil 0x0000000000000000
_subviewCache NSArray * #"0 objects" 0x00000001740033b0
_charge float 0 0
_tag NSInteger 0 0
_viewDelegate UIViewController * nil 0x0000000000000000
_backgroundColorSystemColorName NSString * nil 0x0000000000000000
_countOfMotionEffectsInSubtree NSUInteger 0 0
_viewFlags <anonymous struct>
There is nothing Wrong with UILabel, the problem, I guess, is the format of the "commnad" is not compatible with the text in UILabel.
Try follow code for the delegate function:
-(void)commandEntered:(NSString *)command{
dispatch_async(dispatch_get_main_queue(), ^{
NSString* str1=#"";
NSString* str=[str1 stringByAppendingString:command];
showReceivedCommand.text = str;
});
}
Related
I am trying yo pass data of two textfields in secondViewController to ViewController and set text of labels in ViewController.
But the delegate method for passing data is not being called. I have checked it by putting break point. Hence label text is not changing.
SecondViewController.h
#import <UIKit/UIKit.h>
#class SecondViewController;
#protocol SecondViewDelegate <NSObject>
-(void)getText1:(NSString*)str1 andText2:(NSString*)str2;
#end
#interface SecondViewController : UIViewController<UITextFieldDelegate>
#property (weak, nonatomic) IBOutlet UITextField *textField1;
#property (weak, nonatomic) IBOutlet UITextField *textField2;
#property (weak) id<SecondViewDelegate>delegate;
#end
SecondViewController.m
#import "SecondViewController.h"
#interface SecondViewController ()
#end
#implementation SecondViewController
#synthesize delegate=_delegate;
- (void)viewDidLoad {
[super viewDidLoad];
self.textField1.delegate=self;
self.textField2.delegate=self;
[self.textField1 becomeFirstResponder];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
if ( textField == self.textField1 ) { [self.textField1 resignFirstResponder]; [self.textField2 becomeFirstResponder]; }
else if ( textField == self.textField2) {
[_delegate getText1:self.textField1.text andText2:self.textField2.text];
NSLog(#"%#",self.textField1.text);
[self.navigationController popToRootViewControllerAnimated:YES];
}
return YES;
}
#end
View Controller.h
#import <UIKit/UIKit.h>
#import "SecondViewController.h"
#interface ViewController : UIViewController<SecondViewDelegate>
-(void)getText1:(NSString *)str1 andText2:(NSString *)str2;
#end
View Controller.m
#import "ViewController.h"
#interface ViewController ()
#property (weak, nonatomic) IBOutlet UILabel *label1;
#property (weak, nonatomic) IBOutlet UILabel *label2;
#end
#implementation ViewController
#synthesize label1;
#synthesize label2;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)onClick:(id)sender {
SecondViewController* sv= [[SecondViewController alloc] init];
sv.delegate=self;
[self performSegueWithIdentifier:#"moveToSecondController" sender:self];
}
-(void)getText1:(NSString *)str1 andText2:(NSString *)str2{
[label1 setText:str1];
[label2 setText:str2];
}
#end
The problem is that you've created two SecondViewController objects and made your ViewController the delegate of the wrong one.
This: [[SecondViewController alloc] init] creates an object in code. This: [self performSegueWithIdentifier:#"moveToSecondController" sender:self] creates an object from a storyboard definition.
Don't bother creating the first one, just perform the segue. Then, implement the prepareForSegue method and set your delegate there, using the destination controller (which will be the correct SecondViewController).
Try setting your delegate in prepareForSegue method like:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Make sure your segue name in storyboard is the same as this line
if ([[segue identifier] isEqualToString:#"YOUR_SEGUE_NAME_HERE"])
{
// Get reference to the destination view controller
SecondViewController *vc = [segue destinationViewController];
vc.delegate=self;
}
}
You don't need to declare your delegate method in ViewController.h. It has already been done in SecondViewController.h as the delegate method.
import
import "SecondViewController.h"
#interface ViewController : UIViewController
// Remove this method in ViewController.h file this is call as a simple method for ViewController class
-(void)getText1:(NSString *)str1 andText2:(NSString *)str2;
#end
I have a big noob problem. I new in iOS and I'm trying to do this:
I have two ViewControllers. The first one has an button that if it is pushed, control goes to a second view controller.
That works but the problem is when I try to get data in my second view controller. The UITextfield doesn't work.
I'm trying to display which I insert into textfield in the label. But THE TEXTFIELD DOESN'T WORK :(
I putted the IBOutlets succesfully in the xibs and connect the buttons with their IBActions...
This is my code:
ViewController.h
#import <UIKit/UIKit.h>
#import "SecondViewController.h"
#class SecondViewController;
#interface ViewController : UIViewController
#property (strong, nonatomic) SecondViewController *secondViewController;
-(IBAction)buttonClicked:(id)sender;
#end
ViewController.m
#import "ViewController.h"
#implementation ViewController
#synthesize secondViewController;
-(IBAction)buttonClicked:(id)sender {
self.secondViewController = [[SecondViewController alloc]initWithNibName:#"SecondViewController" bundle:nil];
[self presentViewController:self.secondViewController animated:YES completion:nil];
}
SecondViewController.h
#import <UIKit/UIKit.h>
#interface SecondViewController : UIViewController {
IBOutlet UITextField *textField;
UIButton *obtener;
IBOutlet UILabel *label;
}
#property (nonatomic, retain) IBOutlet UITextField *textField;
#property (nonatomic, retain) IBOutlet UIButton *obtener;
#property (nonatomic, retain) IBOutlet UILabel *label;
-(IBAction)obtenerClicked:(id)sender;
#end
SecondViewController.m
#import "SecondViewController.h"
#implementation SecondViewController
#synthesize obtener, textField, label;
-(IBAction)obtenerClicked:(id)sender {
label.text = textField.text;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// 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 YES for supported orientations
return YES;
}
#end
In your SecondViewController.h, add this property:
#property(nonatomic, readwrite) NSString* myString;
now in firstViewController's onClick method, add this line
-(IBAction)buttonClicked:(id)sender {
//....... Previous code....
self.secondViewController.myString= #"String to be sent";
}
This will pass the string for you..
if you want to pass the string in text field, use this:
-(IBAction)buttonClicked:(id)sender {
//....... Previous code....
self.secondViewController.textField.text= #"String to be sent";
}
hope it will work fine for your requirement.
UPDATE:
Do the following to get expected results:
1. make your secondViewController a textView delegate.
in your secondViewController.h
replace #interface SecondViewController : UIViewController with #interface SecondViewController : UIViewController<UITextFieldDelegate>
put a button in your secondViewController & create an IBAction for it.
on Click event of button, write this:
self.label.text= self.textfield.text;
tell me if it does not work.
I am developing application for iOS7 in xcode 5. I have a view controller ADMSViewController
The .h file is as follows
#import <UIKit/UIKit.h>
#import "IMTWebView.h"
#interface ADMSViewController : UIViewController <UIWebViewDelegate,IMTWebViewProgressDelegate>
{
NSString *barcode;
NSString *vinNumber;
NSTimer *timer;
}
#property (nonatomic,retain) IBOutlet UIWebView *webView;
#property (nonatomic,retain) IBOutlet UIProgressView *progressView;
#end
The .m file is as follows
#import "ADMSViewController.h"
#import <QuartzCore/QuartzCore.h>
#implementation ADMSViewController
#synthesize webView;
#synthesize progressView;
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://google.com/"]]];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.navigationController setNavigationBarHidden:YES animated:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)webView:(IMTWebView *)_webView didReceiveResourceNumber:(int)resourceNumber totalResources:(int)totalResources {
[self.progressView setProgress:((float)resourceNumber) / ((float)totalResources)];
if (resourceNumber == totalResources) {
_webView.resourceCount = 0;
_webView.resourceCompletedCount = 0;
}
}
- (void)viewDidUnload
{
[super viewDidUnload];
self.webView = nil;
self.progressView = nil;
}
#end
The IMTWebview.h file is as follows
#import <UIKit/UIKit.h>
#class IMTWebView;
#protocol IMTWebViewProgressDelegate <NSObject>
#required
- (void) webView:(IMTWebView*)webView didReceiveResourceNumber:(int)resourceNumber totalResources:(int)totalResources;
#end
#interface IMTWebView : UIWebView {
}
#property (nonatomic, assign) int resourceCount;
#property (nonatomic, assign) int resourceCompletedCount;
#property (nonatomic, assign) id<IMTWebViewProgressDelegate> progressDelegate;
#end
the IMTWebCiew.m file is as follows
#import "IMTWebView.h"
#interface UIWebView ()
-(id)webView:(id)view identifierForInitialRequest:(id)initialRequest fromDataSource:(id)dataSource;
-(void)webView:(id)view resource:(id)resource didFinishLoadingFromDataSource:(id)dataSource;
-(void)webView:(id)view resource:(id)resource didFailLoadingWithError:(id)error fromDataSource:(id)dataSource;
#end
#implementation IMTWebView
#synthesize progressDelegate;
#synthesize resourceCount;
#synthesize resourceCompletedCount;
-(id)webView:(id)view identifierForInitialRequest:(id)initialRequest fromDataSource:(id)dataSource
{
[super webView:view identifierForInitialRequest:initialRequest fromDataSource:dataSource];
return [NSNumber numberWithInt:resourceCount++];
}
- (void)webView:(id)view resource:(id)resource didFailLoadingWithError:(id)error fromDataSource:(id)dataSource {
[super webView:view resource:resource didFailLoadingWithError:error fromDataSource:dataSource];
resourceCompletedCount++;
if ([self.progressDelegate respondsToSelector:#selector(webView:didReceiveResourceNumber:totalResources:)]) {
[self.progressDelegate webView:self didReceiveResourceNumber:resourceCompletedCount totalResources:resourceCount];
}
}
-(void)webView:(id)view resource:(id)resource didFinishLoadingFromDataSource:(id)dataSource
{
[super webView:view resource:resource didFinishLoadingFromDataSource:dataSource];
resourceCompletedCount++;
if ([self.progressDelegate respondsToSelector:#selector(webView:didReceiveResourceNumber:totalResources:)]) {
[self.progressDelegate webView:self didReceiveResourceNumber:resourceCompletedCount totalResources:resourceCount];
}
}
#end
My issue is that the progress bar is not animating in the webview. Please help me as I am a newbie to ios development. If there is any other method to implement the same, do inform me.
Thank you in advance for your answers.
For this kind of thing, you can only really 'detect' page size by using Content-Length headers, but otherwise you can still present a loading control (like one of the moving zebra crossing type bars which doesn't show a discrete % progress but shows that activity is occurring.. or even just a UIActivityIndicator). You could try a ready-made class like http://allseeing-i.com/ASIHTTPRequest/ASIWebPageRequest too, which CAN show progress. The author states:
ASIWebPageRequests do not currently support progress tracking for an entire request with its external resources. However, progress updates from external resource requests are passed on to your delegate, so with a bit of work it may be possible to implement this yourself.
I have created a very basic application using the Utility Application template in Xcode 4.2 in which I want an integer variable obtained from a slider or text field in my FlipsideViewController available in my MainViewController.
I have been searching for hour on global variables but can't find a nice simple answer that works for my specific case.
Please help
(note: I am very new at developing for IOS and objective C. Dumb your answer down for me as much as you are capable!)
Thanks a lot
The following is a basic version of my code showing what I want to do.
FlipSideViewController.h
#import <UIKit/UIKit.h>
#class FlipsideViewController;
#protocol FlipsideViewControllerDelegate
- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller;
#end
#interface FlipsideViewController : UIViewController
#property (weak, nonatomic) id <FlipsideViewControllerDelegate> delegate;
- (IBAction)done:(id)sender;
- (IBAction)sliderChange:(id)sender;
#property (weak, nonatomic) IBOutlet UILabel *sliderValueOnFlipside;
#end
FlipSideViewController.m
#import "FlipsideViewController.h"
#interface FlipsideViewController ()
#end
#implementation FlipsideViewController
#synthesize sliderValueOnFlipside;
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)viewDidUnload
{
[self setSliderValueOnFlipside:nil];
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#pragma mark - Actions
- (IBAction)done:(id)sender
{
[self.delegate flipsideViewControllerDidFinish:self];
}
- (IBAction)sliderChange:(id)sender {
UISlider *slider = (UISlider *) sender;
int var = [slider value];
sliderValueOnFlipside.text = [NSString stringWithFormat:#"Slider Value is %d",var];
}
#end
MainViewController.h
#import "FlipsideViewController.h"
#interface MainViewController : UIViewController <FlipsideViewControllerDelegate>
- (IBAction)showInfo:(id)sender;
#property (weak, nonatomic) IBOutlet UILabel *sliderValueOnMain;
#end
MainViewController.m
#import "MainViewController.h"
#interface MainViewController ()
#end
#implementation MainViewController
#synthesize sliderValueOnMain;
- (void)viewDidLoad
{
[super viewDidLoad];
sliderValueOnMain.text = [NSString stringWithFormat:#"Slider Value from flipside is %d", var];
}
- (void)viewDidUnload
{
[self setSliderValueOnMain:nil];
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#pragma mark - Flipside View
- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller
{
[self dismissModalViewControllerAnimated:YES];
}
- (IBAction)showInfo:(id)sender
{
FlipsideViewController *controller = [[FlipsideViewController alloc] initWithNibName:#"FlipsideViewController" bundle:nil];
controller.delegate = self;
controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:controller animated:YES];
}
#end
I can easily get the value of the slider to be displayed on the flipside view however I also want that value displayed on the main view.
Global variables are generally frowned upon in polite programming circles.
If you want a method in MainViewController to react to a change in state in FlipsideViewController, then you could make MVC a delegate of FVC, and have FVC call a method on MVC when the value changes.
There's a good explanation of the delegate design pattern here: http://mobiledevelopertips.com/objective-c/the-basics-of-protocols-and-delegates.html
I am trying to segue to another screen from a uitableview in iOS5. I have set up a delegate etc. which seems to work (the segue occurs) but I think I need to "set delegate to initialize the data I want to display in the new screen. I get a NSInvalidArgumentException error though when I call it is prepareforsegue.
Here is the code for the uitableview part...
#import "iTanksV2ListViewController.h"
#import "tank.h"
#import "tankDetailViewController.h"
#interface iTanksV2ListViewController ()
#property tank *selectedTank;
#end
#implementation iTanksV2ListViewController
#synthesize tanks = _tanks;
#synthesize tankTableView = _tankTableView;
#synthesize delegate = _delegate;
#synthesize selectedTank = _selectedTank;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.tankTableView.delegate = self;
self.tankTableView.dataSource = self;
}
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:#"Show Tank Details"])
{
UILabel *myLabel = [[UILabel alloc] init];
myLabel.text = self.selectedTank.tankNumber;
[segue.destinationViewController setTankNumberLabel:myLabel];
[segue.destinationViewController setDelegate:self]; ///this is where it fails!!!
}
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
self.selectedTank = [self.tanks objectAtIndex:indexPath.row];
[self.delegate iTanksListViewController:self choseTank:self.selectedTank];
}
and then in the detail view I use the following...
-(void)iTanksListViewController:(iTanksV2ListViewController *)sender choseTank:(id)tank
{
self.tankToShow = tank;
}
but this doesn't get called - presumably because i don't successfully call the setdelegate method?!
You must not have synthesized your delegate property. Also, make sure that your header file properly has the delegate protocol referenced like
#interface TankDetailViewController : UITableViewController <DELEGATEPROTOCOL>
I thought I had... this snippet is from the itanksv2listviewcontroller header:
#interface iTanksV2ListViewController : UITableViewController
#property (nonatomic, strong) NSArray *tanks;
#property (weak, nonatomic) IBOutlet UITableView *tankTableView;
#property (weak, nonatomic) id <iTanksV2ListViewControllerDelegate> delegate;
#end
and this from the m file :
#synthesize delegate = _delegate;
and this is what I have put in the detailview m file:
#interface tankDetailViewController () <iTanksV2ListViewControllerDelegate>
#end