(I know this has been asked before, unfortunately none of the related StackOverflow answers I've looked through and tried out while trying to figure this problem out have worked for me. Any help would be much appreciated.)
I'm building a simple news app. The opening screen grabs the latest news entry using Parse's API.
And when you tap the menu button, you get a UITableView of past news days:
I want to be able to pass the id from the selected Parse table cell back to the main view.
I'm using ECSlidingViewController for the sliding menu and a Storyboard for the various screens:
But because of the way I'm using ECSlidingViewController, I can't figure out how to pass data via segues like I otherwise would be able to, so I'm trying to just pass it via the view controllers with a custom init.
Here's my MainViewController.h code:
#interface MainViewController : UIViewController
#property (nonatomic) NSString *detailId;
- (id)initWithDetailId:(NSString*)theId;
#end
Here's my didSelectRowAtIndexPath code in MenuViewController.m:
MainViewController *mainVC = [[MainViewController alloc] initWithDetailId:#"test"];
[self.navigationController pushViewController:mainVC animated:YES];
Here's MainViewController.m's initWithDetailId:
- (id)initWithDetailId:(NSString*)theId
{
NSLog(#"initWithDetailId");
self = [super initWithNibName:nil bundle:nil];
if (self) {
detailId = theId;
}
return self;
}
And here's MainViewController.m's viewDidLoad:
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"detailId equals: %#", self.detailId);
}
But all I get from the NSLog is "detailId equals: (null)". What am I doing wrong here? Thanks!
you have forgot to put self. in front of detailId = theId;
self.detailId = theId;
that is
- (id)initWithDetailId:(NSString*)theId
{
NSLog(#"initWithDetailId");
self = [super initWithNibName:nil bundle:nil];
if (self) {
self.detailId = theId;
}
return self;
}
there is one another method of doing this:
MainViewController *mainVC = [self.storyBoard instantiateViewControllerWithIdentifier:#"yourIdentifier"];
mainVc.detailId=#"test";
[self.navigationController pushViewController:mainVC animated:YES];
Related
I'm trying to get my app to go to the next screen. I eneded up creating a simple test app with 2 screens
On the first vue I have a button connected to the following code to call up the next screen
- (IBAction)atest:(id)sender {
if (mHome == nil)
mHome = [[cHome alloc] initWithNibName:#"cHome" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:mHome animated:YES];
}
I put a break point to make sure the code exicutes, it does but..... the next screen does not come up.
complete code
#import <UIKit/UIKit.h>
#interface cHome : UIViewController{
}
- (IBAction)atest:(id)sender;
#end
#interface cHome ()
#end
#implementation cHome
- (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.
}
- (IBAction)atest:(id)sender
{
[self.navigationController popToRootViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
Just like to add onto Unkn0wn and demonstrate how I presented certain views in an app.
Add a storyboard id for your view controller
click on your view controller in your storyboard hierarchy
click the identity inspector
add a storyboard id as a string in the storyboard id box
I then did something like this in my code:
[self presentViewController:[self.storyboard nstantiateViewControllerWithIdentifier:#"Paint"] animated:NO completion:nil];
obviously, your identifier would not be "Paint" but that's what I used. This was my simplist approach, hope it helps good luck!
NOTE: I did not use navigation controllers in my app.
EDIT
would like to point out, that this method kind of makes the controller appear out of nowhere with no animation (I had special animation for my controls as a transition between view controllers so I didn't need to animate the controller itself)
If you want to push a view controller, you can easily create a push segue, from your first view controller to your second view controller, and then push using
[self performSegueWithIdentifier:#"yourSegueIdentifier" sender:self];
"push segues" can be created both via code or in your storyboard file.
You have a mistake in your code:
mHome = [[cHome alloc] initWithNibName:#"cHome" bundle:[NSBundle mainBundle]];
I think it's the nib name. It should be mHome not cHome.
mHome = [[cHome alloc] initWithNibName:#"mHome" bundle:[NSBundle mainBundle]];
You basically cannot push two of the same view controller on one navigation controller.
I'm fairly new to Objective-C, programming. The one thing, I'm currently putting up with is passing a value from the first ViewController to the next one.
I've read this entry here and it didn't help me. Which is funny, since his answer has nearly 500 votes, so I must be the problem. What I did was the following.
I opened my PreviewViewController.m and added the following line #import "MainViewController.h" since I wanted to pass a value from the PreviewViewController to the `MainViewController. Then, when I switch the layouts ( which successfully works ) I want to pass a value.
MainViewController *mainViewController = [[MainViewController alloc] initWithNibName:#"MainViewController" bundle:nil];
mainViewController.userId = #"539897197";
As you can see, I want to pass the userId. For that, I also created a property in the MainViewController.h
#property ( nonatomic, strong ) NSString *userId;
Now, In my MainViewController.m I want to access the userId. But when I log it, the console tells me it is null. However, when I set the variable right before the NSLog it works, so it seems like the passing is the problem.
Additionally in the MainViewController.m I have the following line
#synthesize userId = _userId;
but even when I removed that line and changed the NSLog to NSLog(#"%#",self.userId); the same problem occurred.
How can I successfully pass the variables? Which step am I doing wrong?
EDIT
This is how I switch the layouts
UIViewController *viewController = [[MainViewController alloc]init];
MainViewController *mainViewController = [[MainViewController alloc] initWithNibName:#"MainViewController" bundle:nil];
mainViewController.userId = #"539897197";
[self presentViewController:viewController animated:YES completion:NULL];
Why not create a custom initializer and pass it in that way? Something like
- (id)initWithUserId:(NSString *)aUserId {
self = [super initWithNibName:#"MainViewController" bundle:nil];
if (self) {
self.userId = aUserId
}
return self;
}
Then you can just do:
MainViewController *mvc = [[MainViewController alloc] initWithUserId:#"1234"]
[self presentViewController:mvc animated:YES completion:nil];
If you are using storyboard then you should use prepareForSegue: method to pass data between view controllers. First Create the segue from your PreviewViewController to MainViewController, just control drag from your view controller to next viewcontroller to create segue. Use UINavigationController if you are using push segue. Use this method to segue and pass data
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if([segue.identifier isEqualToString:#"yourSegueIndentifier"]){
MainViewController *mvc = (MainViewController *) segue.destinationViewController;
mvc.userId = #"539897197";;
}
}
UIViewController *viewController = [[MainViewController alloc]init];
MainViewController *mainViewController = [[MainViewController alloc] initWithNibName:#"MainViewController" bundle:nil];
mainViewController.userId = #"539897197";
[self presentViewController:mainViewController animated:YES completion:NULL];
use mainViewController rather than viewController when presenting the view controller
Here we have two ways for passing data.
First is Custom Delegate
Second is NSNotification
Here we have two view controllers.
ViewController
and
SecondViewController
in SecondViewController
.h
#import <UIKit/UIKit.h>
#class SecondViewController;
#protocol SecondViewControllerDelegate <NSObject>
- (void)secondViewController:(SecondViewController *)secondViewController didEnterText:(NSString *)text;
#end
#interface SecondViewController : UIViewController
#property (nonatomic, assign)id<SecondViewControllerDelegate> delegate;
#property (nonatomic, strong) IBOutlet UITextField *nameTextField;//It must connect as outlet connection
- (IBAction)doneButtonTapped:(id)sender;
#end
.m
#import "SecondViewController.h"
#interface SecondViewController ()
#end
#implementation SecondViewController
- (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.
}
//Either use NSNotification or Delegate
- (IBAction)doneButtonTapped:(id)sender;
{
//Use Notification
[[NSNotificationCenter defaultCenter] postNotificationName:#"passingDataFromSecondViewToFirstView" object:self.nameTextField.text];
//OR Custom Delegate
[self.delegate secondViewController:self didEnterText:self.nameTextField.text];
[self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
in ViewController
.h
#import <UIKit/UIKit.h>
#import "SecondViewController.h"
#interface ViewController : UIViewController<SecondViewControllerDelegate>
#property (nonatomic, strong) IBOutlet UILabel *labelName; //You must connect the label with outlet connection
- (IBAction)gotoNextView:(id)sender;
#end
.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//addObserver here...
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(textFromPreviousViewControllerNotificationReceived:) name:#"passingDataFromSecondViewToFirstView" object:nil];
// Do any additional setup after loading the view, typically from a nib.
}
//addObserver Method here....
- (void)textFromPreviousViewControllerNotificationReceived:(NSNotification *)notification
{
// set text to label...
NSString *string = [notification object];
self.labelName.text = string;
}
- (IBAction)gotoNextView:(id)sender;
{
//If you use storyboard
SecondViewController *secondViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"SecondViewController"];
//OR If you use XIB
SecondViewController *secondViewController = [[SecondViewController alloc] initWithNibName:#"SecondViewController" bundle:nil];
secondViewController.delegate = self;
[self.navigationController pushViewController:secondViewController animated:YES];
}
//Calling custom delegate method
- (void)secondViewController:(SecondViewController *)secondViewController didEnterText:(NSString *)text
{
self.labelName.text = text; //Getting the data and assign the data to label here.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
For your understanding the code I create a simple passing data from one second view controller to first view controller.
First we navigate the view from first view controller to second view controller.
After that we send the data from second view controller to first view controller.
NOTE : You can either use NSNotification or Custom Delegate method for sending data from One View Controller to Other View Controller
If you use NSNotification, you need to set the postNotificationName for getting data in button action method.
Next you need to write addObserver in (sending data to your required View Controller) ViewController and call the addObserver method in same View Controller.
If you use custom delegate,
Usually we go with Custom Protocol Delegate and also we need to Assign the delegate here.
Very importantly we have to set the Custom Delegate Method in the Second View Controller.Because where we send the data to first view controller once we click the done button in second view controller.
Finally we must call the Custom Delegate Method in First View Controller, where we get the data and assign that data to label.Now you can see the passed data using custom delegate.
Likewise you can send the data to other view controller using Custom Delegate Methods
I tried and got the solution for passing the value between viewcontroller.
MainViewController *mainVC = [[self storyboard] instantiateViewControllerWithIdentifier:#"MainViewController"];
mainVC.userId = #"539897197";
[self presentViewController:mainVC animated:YES completion:Nil];
or using this way . You don`t use the storyboard use the following its working fine
MainViewController *mainVC = [[MainViewController alloc] init];
mainVC.userId = #"539897197";
[self presentViewController:mainVC animated:YES completion:Nil];
I am trying to get a UITableView to show up after I tap a next button, I can't get it to work...
I don't know why TimesViewController.m isn't working, how do I link it...
-(IBAction)nextView:(UIBarButtonItem *) sender{
[self pushViewController:TimesTableViewController.m animated:YES];
}
You need to read through View Controller programming guide. Essentially, it depends more on your application design. The most common ways of doing this are:
Tap on nextView should present TableView controller modally.
Tap on nextView should push TableView controller in the navigation stack.
With either of the approach, you need to create a separate view controller for your table view which will manage the table view and act as delegate/data source for it.
From within your button action handler you need to do it this way:
-(IBAction)nextView:(UIBarButtonItem *) sender{
MyTableViewController *tableController = [[MyTableViewController alloc] init];
// For #1 above
[self presentViewController:tableController animated:YES completion:^{
// Any code that you want to execute once modal presentation is done
}];
// For #2 above
[self.navigationController pushViewController:tableController animated:YES];
}
EDIT:
Create a initialize method on your MyTableViewController and pass the values while calling it.
- (id)initWithData1:(NSString *)iData1 data2:(NSString *)iData2 {
if ((self = [super init])) {
self.data1 = iData1;
self.data2 = iData2;
}
return self;
}
MyTableViewController *tableController = [[MyTableViewController alloc] initWithData1:#"Some String" data2:#"Another string"];
PS: You could also expose the string property in your header file of MyTableViewController and set it from the callee class
or if you wanna do it programmatically, in your viewDidLoad, after you created your button
[firstsessionButton addTarget:self action:#selector(showtable:) forControlEvents:UIControlEventTouchUpInside];
-(void)showtable:(UIButton *)sender{
TableViewController *tableViewController=[[TableViewController alloc]init];
[self.navigationController pushViewController:tableViewController animated:YES];
}
I've created an app that uses a bunch load of Container views. Today i've found out that embedded segues are not supported in iOS 5 (thanks Xcode for letting me know.)
So right now I have a lot of embedded segues that passes data between one another.
I'm using this code to load ViewControllers inside a UIView instead of the Container from the IB:
RootViewController:
- (void)viewDidLoad
{
[super viewDidLoad];
UIStoryboard* storyboard = [UIStoryboard storyboardWithName:#"MainStoryboard" bundle:nil];
NewsViewController *news = [storyboard instantiateViewControllerWithIdentifier:#"NewsViewControllerID"];
news.view.frame = self.newsSection.bounds;
[self.newsSection addSubview:news.view];
[self addChildViewController:news];
[news didMoveToParentViewController:self];
// Do any additional setup after loading the view.
}
How can I use the above and still pass data to NewsViewController (something like prepare for segue)
I've tried inserting in the above something like
NewsViewController *news = [storyboard instantiateViewControllerWithIdentifier:#"NewsViewControllerID"];
news.view.frame = self.newsSection.bounds;
news.myLabel.text = #"Test";
[self.newsSection addSubview:news.view];
But the label won't change.
I prefer just to pass the data and not use a singleton or delegation.
Thanks
I would recommend creating a public method, from where you could pass the data you need on your NewsViewController controller. Still, the issue right now is that the you are updating the UI before it has been initialised. Also I would recommend you to have a look on how to create content UIViewControllers, because right now you are only adding its UIView. Check this document from Apple, look at the section Implementing a Custom Container View Controller. And this part of the code:
- (void) displayContentController: (UIViewController*) content;
{
[self addChildViewController:content]; // 1
content.view.frame = [self frameForContentController]; // 2
[self.view addSubview:self.currentClientView];
[content didMoveToParentViewController:self]; // 3
}
So in your case, after the step 3 has been made, you could pass the values you want to use inside your NewsViewController.
The problem could be that at the moment you are setting the text of the label, the label is still nil.
Try adding an NSString property to your NewsViewController (e.g. labelText), and in viewDidLoad do self.myLabel.text = self.labelText;.
you have pass the string your next view controller and viewDidLoad you have to the string.
Its not working because your view not yet created and if check the instance of UIlabel it will nil. So you have set the text in your next viewcontroller when it loaded in the memory.
Edit
you have create a property variable of NSString type(textString) in NewsViewController and pass the string as news.textString = #"Test";
and the in ViewDidLoad of NewsViewController set that string to label as myLabel.text = textString;
Better Explanation
-Declare NSString property in the NewsViewController.h
#property (strong, nonatomic) NSString *assignText;
-Instantiate normally, but assign the string and not the label.
UIStoryboard* storyboard = [UIStoryboard storyboardWithName:#"MainStoryboard" bundle:nil];
NewsViewController *news = [storyboard instantiateViewControllerWithIdentifier:#"NewsViewControllerID"];
news.assignText = #"Test";
[self addChildViewController:news];
-Then in your NewsViewController viewDidload, assign the label to the string.
-(void)viewDidLoad {
[super viewDidLoad];
self.myLabel.text = self.assignText;
}
Is is possible to have a UIView preloaded so that it will load faster when the user taps on button to load it? Currently I've got a library of informaiton that I'm attempting to load when the user taps a button, and for now it seems to be "ok" , but it makes the navigation to the page choppy, because of all the information in the library it's loading.
Thanks in advance!
It should be possible to split the setup of a View Controller from code that displays the view after a button is pushed. This will eliminate the lag when the button but the task to setup the view controller still need to be done sometime during execution (You can for example put it in the ViewdidAppear method so it is executed while waiting for the button to be pushed.
Take this code for example:
-(IBAction) button_pushed {
/*setup */
NewVC *vc = [[NewVC alloc] init];
vc.var1 = var1;
vc.var2 = x;
[vc setup];
/*display */
[self.navigationController pushViewController:vc animated:NO];
return;
}
You can split the code that setup the view from the code that displays the view
into :
#synthesize vc;
…..
- (NewVC) setup {
//setup
NewVC *vc1 = [[NewVC alloc] init];
vc.var1 = var1;
vc.var2 = x;
[vc setup];
return(vc1);
}
-(void) ViewDidAppear {
if (setupready) {
vc = [self setup];}
return;
}
-(IBAction) button_pushed:(ID) sender {
//display
[self.navigationController pushViewController:vc animated:NO];
return;
}