UITextFieldDelegate not working - ios

I'm trying to separate the UITextViewDelegate methods from the main class of my project, I created a class to manage the delegate methods, but I can not change the values of the IBOulets from the main class.
I made a test project with a ViewController and a TextFieldController, in the Storyboard I add a text field and a label. What I want to do is change the text of the label when I start to write in the text field. Here is the code:
ViewController.h:
#import <UIKit/UIKit.h>
#import "TextFieldController.h"
#interface ViewController : UIViewController
#property (strong, nonatomic) IBOutlet UITextField *textField;
#property (strong, nonatomic) IBOutlet UILabel *charactersLabel;
#end
ViewController.m:
#import "ViewController.h"
#interface ViewController ()
#property (nonatomic, strong) TextFieldController *textFieldController;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_textFieldController = [[TextFieldController alloc] init];
_textField.delegate = _textFieldController;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#end
TextFieldController.h:
#import <UIKit/UIKit.h>
#import "ViewController.h"
#interface TextFieldController : UIViewController <UITextFieldDelegate>
#end
Text Field Controller.m:
#import "TextFieldController.h"
#interface TextFieldController ()
#property ViewController *viewController;
#end
#implementation TextFieldController
- (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.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (BOOL) textFieldShouldBeginEditing:(UITextField *)textField {
NSLog(#"hello");
_viewController.charactersLabel.text = #"hello";
return YES;
}
#end
When I start writing in the text field the message "Hello" is printed in the log, but the text of the label does not change. I want to know how to change the label text value from the other class.

First change the TextFieldController.h like this:
#import <UIKit/UIKit.h>
#import "ViewController.h"
#interface TextFieldController : NSObject <UITextFieldDelegate>
{
}
#property (nonatomic, assign) ViewController *viewController;
#end
Then change your TextFieldController.m file like this:
#import "TextFieldController.h"
#interface TextFieldController ()
#end
#implementation TextFieldController
- (BOOL) textFieldShouldBeginEditing:(UITextField *)textField {
NSLog(#"hello");
self.viewController.charactersLabel.text = #"hello";
return YES;
}
#end
In the ViewController.m do like that:
#import "ViewController.h"
#interface ViewController ()
#property (nonatomic, strong) TextFieldController *textFieldController;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_textFieldController = [[TextFieldController alloc] init];
_textFieldController.viewController = self;
_textField.delegate = _textFieldController;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#end
This will work but I personally dont like that way you took.
Good luck :)

It's failing because _viewController is nil. You need to assign the viewController property in your delegate in order to support the two way communication.
Also, I'd strongly recommend you make your delegate object a subclass of NSObject, and not UIViewController. It does nothing with controlling views. You can just manually instantiate it in your ViewController objects viewDidLoad.

In TextViewController I don't see where the viewController property (_viewController ivar) is being set so it is probably nil. You should set it when you create the TextViewController instance.

When you are navigating to other controllers using storyboad's segue then you need to implement prepareForSegue method to initialised its properties as follows
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:#"segue for textFieldController"])
{
TextFieldController *_textFieldController = [segue destinationViewController];
_textField.delegate = _textFieldController;
}
}
But I was wondering, why are you setting textFieldDelegate here, why can't you set in TextFieldController's viewDidLoad method as then you didn't you to implement above prepareForSegue method call?
Besides you are keeping strong reference of each other and you are creating strong retain cycle.
One more thing, following code
_textField.delegate = _textFieldController;
will not work, until textFieldController is loaded and its viewDidLoad method is being called as you are only initialising it but its outlets will not be connected until view is loaded into navigation stack.

Related

Delegate method not being called objective C

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

How to make the keyboard disappear programmatically in iOS

I am having trouble getting the keyboard to disappear after entering text. I have many solutions for previous versions of Xcode, but nothing for Xcode 7. My current ViewController.h file looks like:
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UITextFieldDelegate>
#property (strong, nonatomic) IBOutlet UITextField *txtUsername;
#property (strong, nonatomic) IBOutlet UITextField *txtPassword;
#end
My .m file looks like:
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize txtUsername;
#synthesize txtPassword;
- (void)viewDidLoad {
[super viewDidLoad];
self.txtUsername.delegate = self;
self.txtPassword.delegate = self;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (BOOL) textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
#end
I have assigned the delegate from the textField to the ViewController as well.
Update The View I was working with was not assigned to the ViewController class and therefore did not inherit the textFielfShouldReturn method I needed.
Try:
[self.view endEditing:YES];

I need to pass a string from a NSObject class to a UIViewController with a delegate

I need to pass a string from a NSObject class to a UIViewController, I understand that the best way is delegation but the delegate method isn't being called. I'm trying to set the UILabel an DieFacesViewController as the selectedOption from TemporarySelection.
A tableview shows the value of CustomOptionStore, once it's tapped passes its value to TemporarySelection and opens the modal view DieFacesViewCountroller which should, at least in my mind, take the label value from TemporarySelection. The reason I created TemporarySelection is because the DieFacesViewController will be used by other classes, not only by CustomOptionStore, and it will need to load the label from all those classes when different tableViews are selected.
I tried to set the delegate as self in both viewDidLoad and viewWillAppear with no luck, I don't understand if the view loads before being able to call the delegate method or if there's something wrong the way I set the method up.
I've been stuck here for two days, this is the first time I post a question so please forgive me if it's a bit confused.
my delegator class TemporarySelection.h is
#import <Foundation/Foundation.h>
#import "CustomOptionsStore.h"
#class DieFacesViewController;
#protocol TemporarySelectionDelegate <NSObject>
-(void)sendSelection;
#end
#interface TemporarySelection : NSObject
#property (nonatomic, weak) id <TemporarySelectionDelegate> delegate;
#property (nonatomic, strong) NSString *selectedOption;
-(void)addSelection: (CustomOptionsStore *) selection;
#end
and my TemporarySelection.m is
#import "TemporarySelection.h"
#implementation TemporarySelection
-(void)addSelection: (CustomOptionsStore *) selection{
self.selectedOption = selection.description;
[self.delegate sendSelection];
}
#end
the delegate class DiewFacesViewController.h is
#import <UIKit/UIKit.h>
#import "SelectedStore.h"
#import "TemporarySelection.h"
#interface DieFacesViewController : UIViewController <TemporarySelectionDelegate>
#property (strong, nonatomic) IBOutlet UILabel *SelectionName;
#end
and the DieFacesViewController.m is
#import "DieFacesViewController.h"
#interface DieFacesViewController ()
#end
#implementation DieFacesViewController
- (void)viewDidLoad {
TemporarySelection *ts = [[TemporarySelection alloc]init];
ts.delegate = self;
[super viewDidLoad];
}
-(void)sendSelection{
TemporarySelection *ts = [[TemporarySelection alloc]init];
self.SelectionName.text = ts.selectedOption;
}
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:YES];
}
You are not setting the delegate object properly.Check the above code
#import "DieFacesViewController.h"
#interface DieFacesViewController ()<TemporarySelectionDelegate>
{
//global object
TemporarySelection *ts;
}
#end
#implementation DieFacesViewController
- (void)viewDidLoad {
ts = [[TemporarySelection alloc]init];
ts.delegate = self;
[super viewDidLoad];
}
-(void)sendSelection{
//Use the object to extract
self.SelectionName.text = ts.selectedOption;
}
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:YES];
}

UITextField doesn't work in my SecondViewController

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.

NSInvalidArgumentException error occurs when calling setDelegate

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

Resources