Switching ViewControllers, but nothing happens? - iphone

I want to put the code of switching ViewControllers to a single class, which named SwitchController. But nothing happens.
Here is the code:
//AppDelegate.m
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
RootViewController *root = [[RootViewController alloc] init];
[self.window setRootViewController:root];
[self.window makeKeyAndVisible];
return YES;
}
//SwitchController.h
#interface SwitchController : NSObject
#property (strong,nonatomic) RootViewController *rootViewController;
+(SwitchController *)sharedInstance;
-(void)requestToSwitchViewController:(NSInteger)tag;
#end
//SwitchController.m
#import "SwitchController.h"
#import "FirstViewController.h"
#import "SecondViewController.h"
#implementation SwitchController
#synthesize rootViewController = _rootViewController;
-(id)init
{
self = [super init];
if (self == nil)
{
_rootViewController = [[RootViewController alloc] init];
}
return self;
}
+(SwitchController *)sharedInstance
{
static SwitchController *sharedSingleton = nil;
#synchronized([SwitchController class])
{
if(sharedSingleton == nil)
{
sharedSingleton = [[self alloc] init];
}
}
return sharedSingleton;
}
-(void)requestToSwitchViewController:(NSInteger)tag
{
switch (tag)
{
case 1:
{
FirstViewController *first = [[FirstViewController alloc] init];
[self.rootViewController presentViewController:first animated:YES completion:nil];
}
break;
......... //Do something else
default:
break;
}
}
#end
//This is the self.window.rootViewController------RootViewController.m
//In this ViewController's view, there is a button, and on press, it will do the following thing
- (IBAction)pressed:(id)sender
{
[[SwitchController sharedInstance] requestToSwitchViewController:[(UIButton *)sender tag]];
}
So, is there anything wrong with my code?
Why does nothing happens when I press the button?

There may be several issues..
1) Check whether your button outlet is correctly connected to this method -(IBAction)pressed:(id)sender;
2)Add this line after #synthesize in SwitchController.m
static SwitchController *sharedSingleton = nil;
3)change your method like this
+(SwitchController *)sharedInstance
{
if(sharedSingleton == nil)
{
sharedSingleton = [[self allocWithZone:NULL] init];
}
return sharedSingleton;
}
4) Remove this line from the -id(init) method
// You do not need to re-initialize the root view controller
_rootViewController = [[RootViewController alloc] init];
5) Check whether the button is valid. Before calling this method requestToSwitchViewController: check what it logs
UPDATE:
Try like this: (For this, you need to create a property for navigation controller in your appDelegate and synthesize it)
switch (tag)
{
case 1:
{
FirstViewController *first = [[FirstViewController alloc] init];
appDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate.navigationController presentViewController:first animated:YES completion:nil];
}
.....
.........
}

I guess you're just defining the viewController, you need to define the View too. they're different things.

Related

How to reset all tableView data and arrays when click of UIButton?

I have 1 tabbarcontroller have Login and Complete Tab. I want to click on Logout button in LoginTab, all data and tableview in COmplete tab is reset. I used this code but it not work:
In CompleteTab.m:
-(void) viewDidLoad
{
temp = [[NSMutableArray alloc] init];
iduploadArray= [[NSMutableArray alloc] init];
FileCompletedArray = [[NSMutableArray alloc] init];
DiffArr= [[NSMutableArray alloc] init];
_tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
tableData = [[NSArray alloc] initWithObjects:FileCompletedArray,nil];
// [_tableView setAllowsSelection:YES];
//tableView.dataSource = self;
// [self.view addSubview:tableView];
// [self parseXMLFile:#"x"];
NSURL *url1 = [NSURL URLWithString:#"server.com"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL: url1] ;
....
temp = [FileCompletedArray mutableCopy];
_tableView.dataSource = self;
_tableView.delegate=self;
[self.view addSubview:_tableView];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", error);//: %#", operation.responseString);
}
];
[httpClient enqueueHTTPRequestOperation:operation];
}
-(void) resetAll
{
[temp removeAllObjects];
[FileCompletedArray removeAllObjects];
[DiffArr removeAllObjects];
[_tableView reloadData];
}
In LoginTab.m:
- (IBAction)LogoutButton:(id)sender {
login = false;
username.hidden = NO;
pass.hidden = NO;
LoginButton.hidden = NO;
LogoutButton.hidden = YES;
//make all the arrays get reset
username.text =#"";
pass.text = #"";
[completeview resetAll];
}
I debug: when I click on Logout button,it called resetAll() function but each variable is 0x000000. So it cannot reset data and reload tableview. Can you help me? Thanks
Since the logout button is in loginTab, it doesnot have any reference to your completeTab. So you need to keep the completeTab reference some where in your app. Best choice is in appDelegate. Then on logout button click, take this instance and reset all data.
Keep your completab view controller instance in AppDelegate like this
#property (nonatomic, retain) UIViewController *completeTab;
self.completeTab = \\Your complete tab viewcontroller instance.
Then on logout button click
[(AppDelegate *)[[UIApplication sharedApplication] delegate].completTab resetAll]
Hope this helps.
Use the selector to call the reset method like this
[completeview performSelector:#selector(resetAll)];
Please create sample project with Tabbased Application.
====== AppDelegate.m ======
#import "LoginTab.h"
#import "CompleteTab.h"
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
UIViewController *viewController1 = [[[LoginTab alloc] initWithNibName:#"LoginTab" bundle:nil] autorelease];
UIViewController *viewController2 = [[[CompleteTab alloc] initWithNibName:#"CompleteTab" bundle:nil] autorelease];
self.tabBarController = [[[UITabBarController alloc] init] autorelease];
self.tabBarController.viewControllers = #[viewController1, viewController2];
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
return YES;
}
#end
====== LoginTab.m ======
#implementation LoginTab
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"LoginTab", #"LoginTab");
self.tabBarItem.image = [UIImage imageNamed:#"LoginTab"];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (IBAction)LogoutButton:(id)sender {
// Post Notification to CompleteTab Class
[[NSNotificationCenter defaultCenter]
postNotificationName:#"resetAll"
object:self];
}
====== CompleteTab.m ======
#implementation CompleteTab
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"CompleteTab", #"CompleteTab");
self.tabBarItem.image = [UIImage imageNamed:#"CompleteTab"];
}
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(resetAll:)
name:#"resetAll"
object:nil];
return self;
}
- (void) dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
- (void) resetAll:(NSNotification *) notification
{
NSLog(#"Reset All Called");
}
I am able to call resetAll method of CompeteTab using NSNotification Concept. Please follow this code.
I'd also recommend you check out the free Sensible TableView framework as it has such restting functionality out of box.
As for the method [tableView reloadData] : The table view's delegate or data source calls this method when it wants the table view to completely reload its data. It should not be called in the methods that insert or delete rows, especially within a block implemented with calls to beginUpdates and endUpdates.
I believe you are calling the reloadData in resetAll which is updating the FileCompletedArray which provides the dataSource for the table. Can you call it from somewhere else.

App Crashing using popViewControllerAnimated:YES

I am trying to create a back button to return to the main menu of my app, what is happening now, is, once I press the back button, it shows the main menu, but then the app crashes out a second later.
The code I use for back button is;
- (void)backButtonPressed:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
}
From the AppDelegate.m file
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
self.viewController = [[[MenuViewController alloc] initWithNibName:#"MenuViewController_iPhone" bundle:nil] autorelease];
} else {
self.viewController = [[[MenuViewController alloc] initWithNibName:#"MenuViewController_iPad" bundle:nil] autorelease];
}
navigationController = [[myNavigationViewController alloc] initWithRootViewController:self.viewController];
navigationController.navigationBarHidden = YES;
self.window.rootViewController = navigationController;
[self.window makeKeyAndVisible];
return YES;
}
I cannot see where I am going wrong? It seems to call the right screen, yet crashes straight after?
EDIT - Here is MenuViewController.m file;
#import "MenuViewController.h"
#import "MagicAppDelegate.h"
#import "MagicViewController.h"
#interface MenuViewController ()
#end
#implementation MenuViewController
- (void)viewDidLoad
{
self.view.frame = [[UIScreen mainScreen] bounds];
[super viewDidLoad];
// [self initLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)onStart:(id)sender
{
MagicViewController* viewController;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
viewController = [[MagicViewController alloc] initWithNibName:#"MagicViewController_iPhone" bundle:[NSBundle mainBundle]];
else
viewController = [[MagicViewController alloc] initWithNibName:#"MagicViewController_iPad" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:viewController animated:YES];
[viewController release];
}
- (void)dealloc {
[super dealloc];
}
#end
Please use below code,do u want go mainmenuview controller.
[self.navigationController popToRootViewControllerAnimated:YES];
Actually, I don't understand your code: In the statement navigationController = [[myNavigationViewController alloc] initWithRootViewController:self.viewController]; you are sending an alloc to something that seems to be the instance of class UINavigationController, but alloc is a class method. I therefore assume myNavigationViewController is a subclass of UINavigationController (but then is should start with a capital letter).
The new instance returned is then assigned directly, i.e. without using a setter method, to variable navigationController. It is therefore not retained. If your statement returns an autorelease object, it will thus be released as soon as the program returns to the main event loop.
Try thus to use thus a setter method, i.e. self.navigationController = [[myNavigationViewController alloc] initWithRootViewController:self.viewController];

Two table view in one view controller - pushing any view controller is not working

I have two table view in one view controller.
They works great! But they are not pushing to any vc.
Under -(void) viewDidLoad method in my main view controller:
horizontalViewController = [[HorizontalViewController alloc] init];
verticalViewController = [[VerticalViewController alloc] init];
[horizontalTableView setDataSource:horizontalViewController];
[verticalTableView setDataSource:verticalViewController];
[horizontalTableView setDelegate:horizontalViewController];
[verticalTableView setDelegate:verticalViewController];
horizontalViewController.view = horizontalViewController.tableView;
verticalViewController.view = verticalViewController.tableView;
What can I do?
Thanks.
refer a following code. If you want use a pushViewController method.
You must be have a NavigationViewController.
so, your structure is a little complex. one ViewController has number of Two TableViewController. one ViewController is not have NavigationController. NavigaitonViewController necessarily belong to the app when it runs because it should be configured.
TwoTableViewsAppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UINavigationController *naviController = [[[UINavigationController alloc] initWithRootViewController:viewController] autorelease];
[window setRootViewController:naviController];
[window makeKeyAndVisible];
return YES;
}
TwoTableViewsViewController.m
- (void)viewDidLoad {
if (firstController == nil) {
firstController = [[FirstTVContoller alloc] init];
}
if (secondController == nil) {
secondController = [[SecondTVController alloc] init];
}
[firstTable setDataSource:firstController];
[secondTable setDataSource:secondController];
[firstTable setDelegate:firstController];
[secondTable setDelegate:secondController];
firstController.view = firstController.tableView;
secondController.view = secondController.tableView;
firstController.rootViewController = self;
secondController.rootViewController = self;
[super viewDidLoad];
}
FirstTVContoller.h , SecondTVController.h
#import <Foundation/Foundation.h>
#interface FirstTVContoller : UITableViewController <UITableViewDataSource, UITableViewDelegate>{
NSMutableArray *items;
}
#property (nonatomic, retain) UIViewController *rootViewController;
#end
FirstTVContoller.m , SecondTVController.m
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
VerticalDetailViewController *verticalDetailViewController = [[VerticalDetailViewController alloc] initWithNibName:#"VerticalDetailViewController" bundle:nil];
[[self.rootViewController navigationController] pushViewController:verticalDetailViewController animated:YES];
}

XIB file does not appear

Have created a tab application and created the first XIB file which includes a date picker and round rect button. Problem is when I run it, nothing displays in the simulator. Only get one warning for "incomplete implementation" for BidDatePickerViewController in the implementation file which I have commented out.
Here is the code for the files:
ViewController header:
#import <UIKit/UIKit.h>
#interface BiDDatePickerViewController : UIViewController
#property (strong, nonatomic)IBOutlet UIDatePicker *datePicker;
-(IBAction):buttonPressed;
#end
ViewController implementation:
#import "BiDDatePickerViewController.h"
#implementation BiDDatePickerViewController // Incomplete implementation
#synthesize datePicker;
-(IBAction)buttonPressed
{
NSDate *selected = [datePicker date];
NSString *message = [[NSString alloc]initWithFormat:#"The date and time selected is: %#", selected];
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Date And Time Selected"
message:message
delegate:nil
cancelButtonTitle:#"Yes, I did."
otherButtonTitles:nil];
[alert show];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSDate *now = [NSDate date];
[datePicker setDate:now animated:NO];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
self.datePicker = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
AppDelegate.m
import "BiDAppDelegate.h"
#implementation BiDAppDelegate
#synthesize window = _window;
#synthesize rootController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
[[NSBundle mainBundle] loadNibNamed:#"TabBarController" owner:self options:nil];
[self.window addSubview:rootController.view];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
#end
You need to set the rootViewController to show the view controller you want (BiDDatePickerViewController) in the application:didFinishLaunchingWithOptions:
-(BOOL) application: (UIApplication *) application didFinishLaunchingWithOptions (NSDictionary *) launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
[[NSBundle mainBundle] loadNibNamed:#"TabBarController" owner:self options:nil];
[self.window addSubview:rootController.view];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
BiDDatePickerViewController* viewController = [BiDDatePickerViewController new];
[self.window.rootViewController presentModalViewController:viewController animated:NO];
[viewController release];
return YES;
}
-(BOOL) application: (UIApplication *) application didFinishLaunchingWithOptions (NSDictionary *) launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
BiDDatePickerViewController* viewController = [[BiDDatePickerViewController alloc]initWithNibName:#"TabBarController" bundle:nil];
[self.window addSubview:rootController.view];
[self.window makeKeyAndVisible];
[viewController release];
return YES;
}

how to push UIImagePickerController into UINavigationController?

I have following coding in my Program, in AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
myList = [[List alloc] init];
mySettings = [[Settings alloc] init];
myCriteria = [[Criteria alloc] initWithStyle:UITableViewStyleGrouped];
first = [[UINavigationController alloc] initWithRootViewController:myList];
second = [[UINavigationController alloc] initWithRootViewController:mySettings];
third = [[UINavigationController alloc] initWithRootViewController:myCriteria];
myTabBar = [[UITabBarController alloc] init];
myTabBar.view.frame = CGRectMake(0,20,320,460);
UITabBarItem *first1 = [[UITabBarItem alloc] initWithTitle:#"List" image:[UIImage imageNamed:#"list.png"] tag:0];
UITabBarItem *second2 = [[UITabBarItem alloc] initWithTitle:#"My Profile" image:[UIImage imageNamed:#"settings.png"] tag:1];
UITabBarItem *third3 = [[UITabBarItem alloc] initWithTitle:#"Criteria" image:[UIImage imageNamed:#"Criteria.png"] tag:2];
UINavigationController *localNavigationController = [[UINavigationController alloc] initWithRootViewController:myTabBar];
first.tabBarItem = first1;
second.tabBarItem = second2;
third.tabBarItem = third3;
myControllerArray = [[NSArray alloc] initWithObjects:first, second, third, nil];
[myTabBar setViewControllers:myControllerArray];
[myTabBar setCustomizableViewControllers:myControllerArray];
[self.window addSubview:myTabBar.view];
// Add the view controller's view to the window and display.
// [self.window addSubview:viewController.view];
[self.window makeKeyAndVisible];
return YES;
}
Where these three are different classes, now I want to use camera and album, so when I write coding as below on a button target, it won't work
- (void) useCamera
{
if ([UIImagePickerController isSourceTypeAvailable:
UIImagePickerControllerSourceTypeCamera])
{
NSLog(#"If is true");
UIImagePickerController *imagePicker =
[[UIImagePickerController alloc] init];
// [self.navigationController pushViewController:imagePicker animated:YES];
imagePicker.delegate = self;
imagePicker.sourceType =
UIImagePickerControllerSourceTypeCamera;
imagePicker.mediaTypes = [NSArray arrayWithObjects:
(NSString *) kUTTypeImage,
nil];
imagePicker.allowsEditing = NO;
[self.tabBarController setCustomizableViewControllers:[[NSArray alloc]initWithObjects:imagePicker,self,nil]];
[self.tabBarController setViewControllers:[[NSArray alloc]initWithObjects:imagePicker,self,nil]];
//[self presentModalViewController:imagePicker animated:YES]; I tried
//[self.view addSubview:imagePicker.view]; I tried
//self.view=imagePicker.view; I tried
//[myScrollView addSubview:imagePicker]; I tried
//[myView addSubview:imagePicker]; I tried
[imagePicker release];
newMedia = YES;
}
}
I tried all the above ways but they are not working and showing UIImagePickerController,
now what should I do
if anyone in not clear from my question, can ask me again.....
What about [self.view addSubview:imagePicker.cameraOverlayView]
Also, have you tried adding any other view to your self.view? I wonder if the imagePicker is being added, but is not loaded because the view you are adding it to is not being displayed.
Did u try presenting the imagePicker through one of the navigation controllers?
From Reference
Present the user interface by calling the presentModalViewController:animated: method of the currently active view controller, passing your configured image picker controller as the new view controller. On iPad, you can alternatively present the user interface using a popover as described in initWithContentViewController: and “Presenting and Dismissing the Popover” in UIPopoverController Class Reference.
If using GKImagePicker:
[self.view addSubview:self.imagePicker.imagePickerController.view];
You can always do:
let cam = UIImagePickerController()
cam.delegate = self
cam.sourceType = .camera
self.show(cam, sender: nil)
worked for me
Did you try presenting the UIImagePickerController through the tabBarController (UITabBarController inherits from UIViewController)? Assuming that you created a singleton for for your AppDelegate and that the tabBarController is a property of the AppController (for your convenience I added a sample code for the singleton below), the code would look something like this:
AppController.h
#import <UIKit/UIKit.h>
#interface AppController : NSObject <UIApplicationDelegate> {
UITabBarController *tabBarController;
}
// Class methods for convenience
+ (AppController *)sharedAppController;
// *** Properties
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) UITabBarController *tabBarController;
#end
AppController.m
#import "AppController.h"
static AppController *sharedInstance;
#implementation AppController
#synthesize window=_window;
#synthesize tabBarController;
#pragma mark - Initialization
- (id)init
{
// Create the sharedInstance of the application
if (sharedInstance) {
NSLog(#"Error: You are creating a second AppController");
}
[super init];
sharedInstance = self;
return self;
}
+ (AppController *)sharedAppController
{
return sharedInstance;
}
- (void)dealloc
{
[_window release];
[tabBarController release];
[super dealloc];
}
Now in your class, on the useCamera method call the imagePicker by doing this:
- (void)useCamera
{
// YOUR CODE ...
// Place image picker
[[[AppController sharedAppController] tabBarController]
presentModalViewController:imagePicker animated:YES];
// YOUR RELEASE CODE ...
}
Good luck and happy coding!