Can not change text from a label in objective c - ios

I am working on a app in objective c. Now i want a label to change text with the username's name after login. For some reason this don't work
Here is my code
#import "ViewController.h"
#interface ViewController ()
#property (strong, nonatomic) IBOutlet UITextField *userNameTextField;
#property (strong, nonatomic) IBOutlet UITextField *passwordTextField;
#property (strong, nonatomic) IBOutlet UILabel *labelWelkom;
#end
#implementation ViewController
- (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)Login:(id)sender {
if ([_userNameTextField.text isEqualToString:#""] || [_passwordTextField.text isEqualToString:#""]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"alert" message:#"Please Fill all the field" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
return;
}
NSString *strURL = [NSString stringWithFormat:#"http://localhost:8888/swift/login.php?userName=%#&password=%#",_userNameTextField.text, _passwordTextField.text];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
if ([strResult isEqualToString:#"1"])
{
NSString *username = _userNameTextField.text;
_labelWelkom.text = [NSString stringWithFormat:#"Hello %#", username];
UIStoryboard *sb = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
UIViewController *vc = [sb instantiateViewControllerWithIdentifier:#"logedIn"];
vc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:vc animated:YES completion:NULL];
}
else if ([strResult isEqualToString:#"0"])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"alert" message:#"Wrong username / password" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
return;
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"alert" message:#"Server Error" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
return;
}
}
#end
Here is a image of my storyboard
In the left bottom you see my first page after login it loads the second page (upper right corner) in this page is the label that needs to change.

I think you set text of label before creating an instance. Try to assign after creating
UIStoryboard *sb = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
UIViewController *vc = [sb instantiateViewControllerWithIdentifier:#"logedIn"];
vc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:vc animated:YES completion:NULL];
_labelWelkom.text = [NSString stringWithFormat:#"Hello %#", username];

I got some remarks :
.Your _labelWelkom is referring to your Login view controller. Where is the declaration of the loggedIn view label ?
.You defined an IBAction through Interface Builder. So why don't you use
(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
to present your 'loggedIn view' instead of instantiating and presenting this view programmatically here ?
UIStoryboard *sb = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
UIViewController *vc = [sb instantiateViewControllerWithIdentifier:#"logedIn"];
vc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:vc animated:YES completion:NULL];
If we preserve the present IB, let us remind that there is, as far as I know, two main ways to access your label in the second view :
Using IB :
Create another ViewController,i.e .h and .m files.
Link it to your 'Logged in' view controller in IB (through the Identity Inspector)
Link your label as an IBOutlet to your new view controller
In this first case, you should have a class in charge of getting your username after a successful login action. Using NSUserDefault is a way, among others to do this (check Stackoverflow Q&A to get more information).
Programmatically with keeping your IB as it is
Put a tag on your label in IB. Ex : 100.
In this second case, you can put text value to your UILabel within the first view controller implementation.
You can access it after your loggedIn view instantiation through :
UILabel* yourlabel =(UILabel*) [yourView viewWithTag: 100];
Look at this Q&A page :
How can I programmatically access UI elements in a NIB without 'wiring' them?
In this second case, you can put text value to your UILabel within the first view controller implementation.
I hope this will help you.

Related

'UIPopoverController' is deprecated: first deprecated in iOS 9.0 [duplicate]

This question already has answers here:
How can I fix the "UIPopoverController is deprecated" warning?
(4 answers)
Closed 6 years ago.
I have developed a project that shows error :
'UIPopoverController' is deprecated: first deprecated in iOS 9.0 - UIPopoverController is deprecated. Popovers are now implemented as UIViewController presentations. Use a modal presentation style of UIModalPresentationPopover and UIPopoverPresentationController.
My codings are:
ViewController.h:
#import <UIKit/UIKit.h>
#import <Photos/Photos.h>
#import <MobileCoreServices/MobileCoreServices.h>
#interface ViewController : UIViewController
<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
- (IBAction)touch:(id)sender;
#end
#interface SecondView : UIViewController
<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
//video gallery
#property (strong,nonatomic) UIPopoverPresentationController *popOver;
#property (weak, nonatomic) IBOutlet UIView *studentView;
#property (strong, nonatomic) NSURL *videoURL;
#end
ViewController.m:
- (void)openGallery {
UIImagePickerController *Picker=[[UIImagePickerController alloc] init];
Picker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
Picker.mediaTypes=[[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, nil];
Picker.delegate=self;
if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
UIPopoverController *popController=[[UIPopoverController alloc] initWithContentViewController:Picker];
[popController presentPopoverFromRect:CGRectMake(0, 600, 160, 300) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
self.popOver=popController;
}
else
{
[self presentViewController:Picker animated:YES completion:nil];
}
}
#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
if (self.studentView) {
self.videoURL = info[UIImagePickerControllerMediaURL];
[picker dismissViewControllerAnimated:YES completion:NULL];
[[NSUserDefaults standardUserDefaults] setObject:[self.videoURL absoluteString] forKey:#"url1"];
}
}
I could not proper reference for UiModalPresentationPopover. Can someone help me to solve this error. Any help is much appreciated. Thank you.
use UIModalPresentationPopover
In a horizontally regular environment, a
presentation style where the content is displayed in a popover view.
The background content is dimmed and taps outside the popover cause
the popover to be dismissed. If you do not want taps to dismiss the
popover, you can assign one or more views to the passthroughViews
property of the associated UIPopoverPresentationController object,
which you can get from the popoverPresentationController property.
In a horizontally compact environment, this option behaves the same as
UIModalPresentationFullScreen.
Available in iOS 8.0 and later.
Reference UIModalPresentationStyle Reference
for example
ModalViewController *modal = [[ModalViewController alloc] init];
modal.modalPresentationStyle = UIModalPresentationPopover;
modal.transitioningDelegate = self;
modal.popoverPresentationController.sourceView = self.view;
modal.popoverPresentationController.sourceRect = CGRectZero;
modal.popoverPresentationController.delegate = self;
[self presentViewController:modal animated:YES completion:nil];
else use UIPopoverPresentationController
for example
UIPopoverPresentationController *popController = [self. popoverPresentationController];
popController.permittedArrowDirections = UIPopoverArrowDirectionAny;
popController.barButtonItem = self.leftButton;
popController.delegate = self;
additional reference

Objective C - ViewController's functions aren't working when VC is called from button

I have problem with one of the buttons on my Alert View.
- (void)viewDidLoad {
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
if (! [defaults boolForKey:#"notFirstRun"]) {
UIAlertView *welcomeAlert = [[UIAlertView alloc] initWithTitle:#"Welcome!" message:#"This is your first run of Energy Calculator, please select Your default settings first!" delegate:self cancelButtonTitle: #"No, thanks" otherButtonTitles:#"Go to settings", nil];
[welcomeAlert show];
[defaults setBool:YES forKey:#"notFirstRun"];
}
[super viewDidLoad];
}
- (void)alertView:(UIAlertView *)welcomeAlert clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == [welcomeAlert cancelButtonIndex]) {
[welcomeAlert dismissWithClickedButtonIndex:0 animated:NO];
NSLog(#"przycisk 1");
} else if (buttonIndex == 1) {
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
SettingsVC *viewController = [storyboard instantiateViewControllerWithIdentifier:#"SVC"];
[self presentViewController:viewController animated:NO completion:nil];
}
}
When I am using "normal" switch button on my First ViewController, every function on Second Viewcontroler works flawless (i.e. multilpying two values, or even "back" button with simple "dismiss view controller" method).
Mark that, that this "normal" swith button has method "present 2nd view controller modally"
But when I use "Go to settings" button on UIAlertView, none of above functions work. I think the part of the problem is that 2nd view controller is non-modally presented, unlike with help of "normal" switch button.
Any ideas for solutions?
After reviewing Your answers, I decided to try using segue that has been normally used to send data between controllers. I was not aware of that I can use segue once more.
There are my changes - commented lines are all things I tried.
- (void)alertView:(UIAlertView *)welcomeAlert clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == [welcomeAlert cancelButtonIndex]) {
[welcomeAlert dismissWithClickedButtonIndex:0 animated:NO];
NSLog(#"przycisk 1");
} else if (buttonIndex == 1) {
// UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
//SettingsVC *viewController = [storyboard instantiateViewControllerWithIdentifier:#"SVC"];
//[self presentViewController:viewController animated:NO completion:nil];
//[self showDetailViewController:viewController sender:nil];
[self performSegueWithIdentifier:#"settingSegue" sender:nil];
}
}
Can you try moving the UIAlertView code from viewDidLoad method to viewDidAppear method ? in viewDidLoad , current view is not yet in hierarchy and when you are displaying alert-view , it might have confusion in view-hierarchy
so
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
if (! [defaults boolForKey:#"notFirstRun"]) {
UIAlertView *welcomeAlert = [[UIAlertView alloc] initWithTitle:#"Welcome!" message:#"This is your first run of Energy Calculator, please select Your default settings first!" delegate:self cancelButtonTitle: #"No, thanks" otherButtonTitles:#"Go to settings", nil];
[welcomeAlert show];
[defaults setBool:YES forKey:#"notFirstRun"];
}
}
Also , try avoiding UIAlertView , because its deprecated in iOS8+ , use some compatible views to still support iOS 7 , for example https://github.com/ogres/CUIAlertController
and you could easily do the whole process without delegate callbacks :
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
if (! [defaults boolForKey:#"notFirstRun"]) {
NSMutableArray *actions = [[NSMutableArray alloc] init];
[actions addObject:[CUIAlertAction actionWithTitle:#"Go to settings" block:^{
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
SettingsVC *viewController = [storyboard instantiateViewControllerWithIdentifier:#"SVC"];
[self presentViewController:viewController animated:NO completion:nil]
}]];
[actions addObject:[CUIAlertAction actionWithTitle:#"No, thanks" block:nil]];
[CUIAlertController presentAlertViewWithTitle:#"Welcome!"
message:#"This is your first run of Energy Calculator, please select Your default settings first!"
actions:actions
fromController:self
animated:YES];
[defaults setBool:YES forKey:#"notFirstRun"];
}
}

UIDatePicker memory leak in IOS 8.3

I am seeing memory leaks in UIDatePicker when used in a popover on an iPad running IOS 8.3. I'm getting approx 5K in multiple memory leaks every time the date picker is popped up and then dismissed. The leaked object is NSDateComponents, and the responsible frame is [_UIDatePickerMode _yearlessYearForMonth:].
I have written a simple test app to demonstrate the problem (https://github.com/david-ape/datepickertest/). I've included both a UIPopoverController option and a UIPopoverPresentationController option, but it doesn't seem to matter which is used.
Am I doing something wrong, or is there a workaround, or do I need to wait for a fix from Apple? If the latter, then can anyone suggest a third party control that I could use in place of UIDatePicker?
Below is the code I'm using to pop up the date pickers.
Header file
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UIPopoverControllerDelegate,
UIPopoverPresentationControllerDelegate>
#end
Implementation file
#import "ViewController.h"
#interface ViewController ()
#property (nonatomic, strong) UIPopoverController *ios7Popover;
- (IBAction)datePickerPopupIOS7:(UIButton *)sender;
- (IBAction)datePickerPopupIOS8:(UIButton *)sender;
#end
#implementation ViewController
// helper - returns a view controller containing a date picker for use in a
// popup
+ (UIViewController *)buildDatePickerViewController
{
CGRect frame = CGRectMake(0, 0, 350, 216);
UIViewController *viewController = [[UIViewController alloc]init];
viewController.preferredContentSize = frame.size;
UIDatePicker *datepicker = [[UIDatePicker alloc]initWithFrame:frame];
datepicker.datePickerMode = UIDatePickerModeDate;
datepicker.hidden = NO;
datepicker.date = [NSDate date];
[viewController.view addSubview:datepicker];
return viewController;
}
// popup date picker using UIPopoverController (IOS7 compatible)
- (IBAction)datePickerPopupIOS7:(UIButton *)sender
{
UIViewController *viewController = [ViewController buildDatePickerViewController];
self.ios7Popover = [[UIPopoverController alloc]initWithContentViewController:viewController];
self.ios7Popover.delegate = self;
[self.ios7Popover presentPopoverFromRect:sender.frame
inView:self.view
permittedArrowDirections:(UIPopoverArrowDirectionUp|UIPopoverArrowDirectionDown| UIPopoverArrowDirectionLeft|UIPopoverArrowDirectionRight)
animated:YES];
}
// popup date picker using UIPopoverPresentationController (IOS8 or later required)
// Thanks to http://stackoverflow.com/a/26944036/1764243 for how to do this
- (IBAction)datePickerPopupIOS8:(UIButton *)sender
{
if ([UIPopoverPresentationController class])
{
UIViewController *viewController = [ViewController buildDatePickerViewController];
UINavigationController *destNav = [[UINavigationController alloc] initWithRootViewController:viewController];
destNav.modalPresentationStyle = UIModalPresentationPopover;
UIPopoverPresentationController *popover = destNav.popoverPresentationController;
popover.delegate = self;
popover.sourceView = self.view;
popover.sourceRect = [sender frame];
destNav.navigationBarHidden = YES;
[self presentViewController:destNav animated:YES completion:nil];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Not supported"
message:#"UIPopoverPresentationController not supported in this version of IOS"
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alert show];
}
}
#pragma mark - UIPopoverControllerDelegate methods
- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController
{
self.ios7Popover = nil;
}
#end

How to switch to a existing, non-Navigation Controller-View programmable?

I am trying to switch from a View (a totally normal view) to another view (also normal) programmable. Here is my already existing Code:
- (IBAction)login:(id)sender {
if([_username.text isEqualToString:name] && [_password.text isEqualToString:pw]) {
DashboardViewController *destinationController = [[DashboardViewController alloc] init];
[self.navigationController pushViewController:destinationController animated:YES];
}else {
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"Wrong Username or Password!"
message:#"Sorry."
delegate:nil
cancelButtonTitle:#"Okay"
otherButtonTitles:nil, nil];
[message show];
_password.text = nil;
}
}
So, I want to get directed to my DashboardViewController. If I try this code, a black, empty View is shown. What is wrong with it?
I recently had the same problem! Here is the solution I used:
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"MainStoryboard" bundle: nil];
DashboardViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:#"id"];
[self.navigationController pushViewController:viewController animated:YES];
MainStoryboard should be the name of your storyboard and id should be the View Controller ID which you can set in the storyboard.

Trying to access UINavigationController from within AppDelegate

Ok, I'm still pretty new to iOS development, so I apologize if this is a silly question.
But, I have an AlertView that I call from the AppDelegate then respond when clicking a button in the alert. I can do a NSLog and see that the methods are getting called. But, it's not pushing the view into the stack. Here's a sample of what I have (I'm sure it's wrong):
This is in the AppDelegate.m:
#import "AppDelegate.h"
#import "ProfileConnection.h"
#implementation AppDelegate
#synthesize window = _window;
#synthesize navController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
return YES;
}
-(void)switchToController:(NSString *)controller animated:(BOOL)animated{
NSLog(#"switching to controller %#", controller);
// maybe we can do a check to see if a subview exists...and then push or pop accordingly.
// switch to the "TableView" view
if( [controller isEqualToString:#"ProfileConnection"]){
NSLog(#"switching to the ProfileConnection view");
ProfileConnection *profile = [[ProfileConnection alloc] initWithNibName:#"ProfileConnection" bundle:nil];
[self.navController pushViewController:profile animated:YES];
}
}
-(void)showConnectionFoundAlert
{
NSString *connectFoundMsg = [[NSString alloc] initWithFormat:#"We found someone we'd think you would like to meet: Tony Davis"];
UIAlertView *connectionFoundAlert = [[UIAlertView alloc] initWithTitle:#"Connection Found" message:connectFoundMsg delegate:self cancelButtonTitle:#"Decline" otherButtonTitles:#"Connect", #"View Profile", #"Save For Later", nil];
[connectionFoundAlert show];
//[connectionFoundAlert release];
}
-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
NSString *alertString = [[NSString alloc] initWithFormat:#""];
if([title isEqualToString:#"Decline"])
{
alertString = #"Declied";
}
else if([title isEqualToString:#"Connect"])
{
alertString = #"Connected";
}
else if([title isEqualToString:#"View Profile"])
{
//alertString = #"Profile Viewed";
//NSLog(#"View Profile is being called");
[self switchToController:#"ProfileConnection" animated:YES];
//UIViewController *profile = [[UIViewController alloc] initWithNibName:#"ProfileConnection" bundle:nil];
//ProfileConnection *profile = [[ProfileConnection alloc] initWithNibName:#"ProfileConnection" bundle:[NSBundle mainBundle]];
//UINavigationController *nav = [[UINavigationController alloc] init];
//[nav pushViewController:profile animated:NO];
/*UIViewController *profile = [[UIViewController alloc] initWithNibName:#"ProfileConnection" bundle:nil];
UINavigationController *navigation = [[UINavigationController alloc] init];
[navigation pushViewController:profile animated:YES];*/
/*
ProfileConnection *profile = [ProfileConnection alloc];
//UIView *current = self.window;
[self.window addSubview:profile.view];
*/
/*
[window addSubview:view1.view];
[window makeKeyAndVisible];
- (void)goToNextPage {
view2 = [ViewController2 alloc];
UIView *current = self.window;
[self.window addSubview:view2.view];
*/
}
else if ([title isEqualToString:#"Save For Later"])
{
alertString = #"Saved It";
}
UIAlertView *alertStr = [[UIAlertView alloc] initWithTitle:#"" message:alertString delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
if ([alertString isEqualToString:#""]) {
} else {
[alertStr show];
}
}
#end
This is the AppDelegate.h:
#import <UIKit/UIKit.h>
#import "ProfileConnection.h"
#interface AppDelegate : UIResponder <UIAlertViewDelegate, UIApplicationDelegate, UINavigationControllerDelegate> {
UINavigationController *navController;
}
#property (strong, nonatomic) UIWindow *window;
#property (nonatomic, retain) UINavigationController *navController;
-(void)showConnectionFoundAlert;
-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex;
-(void)switchToController:(NSString *)controller animated:(BOOL)animated;
#end
I am able to add the view with this, but I lose my navigation controller:
ProfileConnection *profile = [ProfileConnection alloc];
[self.window addSubview:profile.view];
You can see I have tried a few approaches, but I'm confusing myself trying to use the storyboard approach.
Also, the ProfileConnection view is blank with a single label at the moment, if that helps.
You code looks ok [self.navController pushViewController:profile animated:YES]; is how you should do it.
You should make sure that you have added the navigation controller to the window. Perhaps this should already be done by the storyboard, but if not user the rootviewcontroller property of the window (its better than addSubview).
self.window.rootViewContorller = self.navController;
Now do a sanity check to make sure nothing is nil (profile or the navController).
NSLog(#"%# %#",self.navController, profile);
Does any of that help?

Resources