display date in iphone - iphone

HI, i am developing an application, where the user needs to enter the start date and end date to view the transactions within that specified date range.
please suggest me the best way to display it in iphone.
i saw the date picker , but it occupies most of my scren..

You could have fields for the start and end date and when the user taps on one of the fields, show a detail view with the picker. Checkout how you enter a date and time in the Calendar application.
I also recently saw some application where the date picker was shown as a modal view (scrolled in from the bottom, like a keyboard). Then it only occupies the screen while the user is actually choosing a date and disappears once she is done.
Update: OK, I don't have access to a Mac at the moment and typed this all up in notepad, so it probably won't work unmodified:
First, I'd create a custom UIViewController:
#interface MyDatePickerViewController : UIViewController <UIPickerViewDelegate> {
UITextfield *textfieldBeingEdited;
UIDatePicker *datePicker;
}
#property (nonatomic, assign) UITextfield *textfieldBeingEdited; // not sure about 'assign'
#property (nonatomic, retain) IBOutlet UIDatePicker *datePicker;
- (IBAction)dismiss:(id)sender;
#end
#implementation MyDatePickerViewController
#synthesize textfieldBeingEdited;
- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle {
if (self = [super initWithNibName:nibName bundle:nibBundle]) {
// do other initializations, if necessary
}
return self;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// TODO: get the date from textfieldBeingEdited and set it in the UIDatePicker
// You'd want the correct date preset when the view is animated in
self.datePicker.date = /* the date */;
}
- (void)pickerView:(UIPickerView *)pickerView
didSelectRow:(NSInteger)row
inComponent:(NSInteger)component {
NSDate *date = self.datePicker.date;
// TODO: format the date
NSString *formattedDate = ...;
// update the text field
textfieldBeingEdited.text = formattedDate;
}
- (IBAction)dismiss:(id)sender {
[self dismissModalViewControllerAnimated:YES];
}
#end
When the user taps on one of your date fields, you'd create a UIViewController and show it as a modal view:
UIViewController *datePickerViewController = [[MyDatePickerViewController alloc]
initWithNibName:#"nib name goes here" bundle:nil];
datePickerViewController.textfieldBeingEdited = /*the field with the start date or end date*/;
[self presentModalViewController:datePickerViewController animated:YES];
[datePickerViewController release];
Some comments about the nib file:
the class name of File's Owner would
be MyDatePickerViewController
add a UIDatePicker, connect it to the datePicker outlet, and set it's delegate and so on to File's Owner
add a button so the user can dismiss the view and hook it up to the -dismiss: outlet in MyDatePickerViewController
Update 2: To prevent the keyboard from displaying, I made my view controller the delegate for the UITextField. Then, I present the modal view controller in -textFieldShouldBeginEditing: and return NO. Returning NO stops the keyboard from showing:
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
MyDatePickerViewController *modal = [[MyDatePickerViewController alloc] initWithNibName:nil bundle:nil];
modal.textfieldBeingEdited = self.dateField;
[self presentModalViewController:modal animated:YES];
[modal release];
return NO;
}

Visit the HIG and see what it has to say. iPhone HIG DOC

Related

Your Second iOS App: Edit one object in two different views

I am going through the tutorials provided by Apple and tried to improve "My Second iOS App", the app for bird sightings.
(There is a MasterView where all entered sightings are listed. If you click one, you are directed to a DetailView of the sighting. You can add a sighting and are asked to enter a name and location.)
I want to sepperate the views for entering the birds name and location.
So I have two views (one for entering the name and one for entering the location) and one object I want to store.
In the file BirdSighting.m I added the following methods
-(id)initWithNameOnly:(NSString *)name date:(NSDate *)date
{
self = [super init];
if (self) {
_name = name;
_date = date;
return self;
}
return nil;
}
and
-(id)setLocation:(NSString *)location
{
if (self) {
_location = location;
return self;
}
return nil;
}
In the AddSightingNameViewController.m I implemented the following code
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"ToLocation"])
{
if ([self.birdNameInput.text length])
{
BirdSighting *sighting;
NSDate *today = [NSDate date];
sighting = [[BirdSighting alloc] initWithNameOnly:self.birdNameInput.text date:today];
self.birdSighting = sighting;
}
}
}
The view for entering the name leads with a push segue to the location-view. There has'nt been changed much else.
Now how do I pass the object generated in the first view to the second? And how do I call the setLocation method on this specific object in AddSightingLocationViewController.m? Do I have to define different properties? And how do I finally display the object in the MasterView with the correct data after I entered the location?
As this code is not working yet, I don't even know if it is working, what I am trying to do. So please be gentle, if this is crappy code.
This is the method I have been using:
First you will need to add a property in your destination view controller, to hold the object you want to pass:
#property (strong, nonatomic) BirdSighting *newSighting;
Then change the prepareForSegue method in your first view controller to the following:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"ToLocation"])
{
if ([self.birdNameInput.text length])
{
BirdSighting *sighting;
NSDate *today = [NSDate date];
sighting = [[BirdSighting alloc] initWithNameOnly:self.birdNameInput.text date:today];
self.birdSighting = sighting;
// Get destination view
YourDestinationViewController *vc = (YourDestinationViewController *)segue.destinationViewController;
// Pass birdSighting object to your destination view controller
[vc setNewSighting:self.birdSighting];
}
}
}
I think I originally got this method from this question
It is also worth noting that the BirdSighting class has a location #property in it's .h file & you will notice the #synthesize line in the .m file.
The #synthesize directive automatically creates accessor methods for you:
#property (nonatomic, copy) NSString *location;
Has the following methods automatically generated (but not visible in the file):
- (NSString *)location;
- (void)setValue:(NSString *)location;
Therefore it was unnecessary for you to override the setter method for location in the BirdSighting.m file with:
-(id)setLocation:(NSString *)location
If you remove that method (note that it should return void not id) you should now be able to access the location variable in a BirdSighting object in the following way:
// In this example we are accessing a BirdSighting #property (hence the use of self.sighting)
// #property (strong, nonatomic) BirdSighting *sighting;
// Getter - returns (NSString *)location of the BirdSighting object
[self.sighting location];
// Setter - sets the location property of the BirdSighting object to 'newLocation'
[self.sighting setLocation:newLocation];
Hope this clears some things up for you!

iOS - Passing variable to view controller

I have a view with a view controller and when I show this view on screen, I want to be able to pass variables to it from the calling class, so that I can set the values of labels etc.
First, I just tried creating a property for one of the labels, and calling that from the calling class. For example:
SetTeamsViewController *vc = [[SetTeamsViewController alloc] init];
vc.myLabel.text = self.teamCount;
[self presentModalViewController:vc animated:YES];
[vc release];
However, this didn't work. So I tried creating a convenience initializer.
SetTeamsViewController *vc = [[SetTeamsViewController alloc] initWithTeamCount:self.teamCount];
And then in the SetTeamsViewController I had
- (id)initWithTeamCount:(int)teamCount {
self = [super initWithNibName:nil bundle:nil];
if (self) {
// Custom initialization
self.teamCountLabel.text = [NSString stringWithFormat:#"%d",teamCount];
}
return self;
}
However, this didn't work either. It's just loading whatever value I've given the label in the nib file. I've littered the code with NSLog()s and it is passing the correct variable values around, it's just not setting the label.
Any help would be greatly appreciated.
EDIT: I've just tried setting an instance variable in my designated initializer, and then setting the label in viewDidLoad and that works! Is this the best way to do this?
Also, when dismissing this modal view controller, I update the text of a button in the view of the calling ViewController too. However, if I press this button again (to show the modal view again) whilst the other view is animating on screen, the button temporarily has it's original value again (from the nib). Does anyone know why this is?
When a view controller is being initialized, inside the initWithNibName method, the views that reside in the view controller aren't yet initialized and you can't set their properties yet. Do whatever you need that is view based in the "viewDidLoad" method.
I am not a pro but this may help you.
In the header view1.h, declare the desired property:
// view1.h
#interface view1 : UIViewController {
NSString *passingVariable;
}
#property (nonatomic, strong) NSString *passingVariable;
#end
and then in the implementation of view1, synthesize the variable:
// view1.m
#implementation view1
#synthesize passingVariable;
// the rest of the implementation
#end
and, finally in the implementation of the other view controller, view2:
// view2.m
#import "view1.h"
#implementation view2
-(IBAction)changeview
{
view1 *myview = [[view1 alloc] init];
myview.passingVariable = #"Hello Variable";
[self.navigationController pushViewController:myview animated:YES];
}
#end
here i am trying to move from view2 to view 1 and also initializing the passingVariable ivar of view1. hope this will help you.
Here i'm passing the ViewController's label text to SecondViewController's Label Text
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
{
// please make your control on XIB set these IBOutlet's
//I'm not showing how to connect these with XIB
IBOutlet UILabel *lblView;
IBOutlet UIButton *buttonGo;
}
//this is method which will push the view
-(IBAction)buttonGoClickAction:(id)sender;
ViewController.m
-(IBAction)buttonGoClickAction:(id)sender
{
SecondViewController *secondViewObject = [[SecondViewController alloc]initWithNibName:#"SecondViewController" bundle:nil];
//before pushing give the text
secondViewObject.string = lblView.text;
[self.navigationController pushViewController:secondViewObject animated:YES];
}
SecondViewController.h
#import <UIKit/UIKit.h>
#interface SecondViewController : UIViewController
{
IBOutlet UILabel *labelView;
NSString *string;
}
//set the string property
#property(nonatomic, retain) NSString *string;
#end
SecondViewController.m
#import "SecondViewController.h"
#implementation SecondViewController
//synthesize string here
#synthesize string;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
//Here you will get the string
labelView.text = string;
}
Firstly you check that have you attach this label IBOutlet in xib or not if you made it via Interface Builder....
use it like this....
SetTeamsViewController *vc = [[SetTeamsViewController alloc] initWithTeamCount:teamCount];
Take a string variable in .h file and set that string here .. NSSting *str in .h
- (id)initWithTeamCount:(int)teamCount {
self = [super init];
if (self) {
// Custom initialization
str = [NSString stringWithFormat:#"%d",teamCount];
}
return self;
}
and set your label in viewDidLoad: or in viewWillApear:
self.teamCountLabel.text = str;
May this will help you
As said by stavash, control in the xib are created in the view did load. To be more precise, they are created with that line :
[super viewDidLoad];
So, mylabel doesn't exist before that time (it is nil).
The easiest way is to do that :
SetTeamsViewController *vc = [[SetTeamsViewController alloc] init];
[self presentModalViewController:vc animated:YES];
vc.myLabel.text = self.teamCount;
[vc release];
The longer but more correct path is to have a member NSString* in SetTeamsViewController class, to set it to teamCount before showing the window, and in the view did load to put that membre value in your label.
Cdt
It depends on your need. You can use Singleton class for sharing of your variables between different classes. Define all variable which you wants share in your DataClass.
in .h file (where RootViewController is my DataClass, replace name with your new class)
+(RootViewController*)sharedFirstViewController;
in .m file
//make the class singleton:-
+(RootViewController*)sharedFirstViewController
{
#synchronized([RootViewController class])
{
if (!_sharedFirstViewController)
[[self alloc] init];
return _sharedFirstViewController;
}
return nil;
}
+(id)alloc
{
#synchronized([RootViewController class])
{
NSAssert(_sharedFirstViewController == nil,
#"Attempted to allocate a second instance of a singleton.");
_sharedFirstViewController = [super alloc];
return _sharedFirstViewController;
}
return nil;
}
-(id)init {
self = [super init];
if (self != nil) {
// initialize stuff here
}
return self;
}
after that you can use your variable in any other class like this
[RootViewController sharedFirstViewController].variable
Hope it's help you:)
With Storyboards the the right way is to pass the indexPath as sender argument in performSegueWithIdentifier
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self performSegueWithIdentifier:#"segueIdentifier" sender:indexPath];
}
and to set a property in the destination controller:
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString: #"segueIdentifier"]) {
NSIndexPath *indexPath = sender;
DetailViewController *dest = [segue destinationViewController];
dest.usersArray = [self.usersArray objectAtIndex:indexPath.row];
}
}
What I have done whenever I needed another class to have the variables from the previous class I either set up a global class that will store the values incase I need them in more locations or in the interface you can set #public variables. These variables can be set using the controller that you created for the next view as such.
controller->pub_var1 = val1;
controller->pub_var2 = val2;
This will be done before you pass the view to the root controller or just before you call the next view. You will need to #import "class.h" so that you can access those public variables.
I can show code if this is not clear

Trying to pass data between viewControllers

I have a sequence of 4 viewControllers inside a NavigationController, each grabs a few textFields of input from the user which are stored in a NSMutableDictionary.
Each of the VC's set's itself up as the delegate of the nextVC before it segues, it also passes the NSMutDict along.
This works fine.
What I don't understand is this:
Say I have filled in the 5 textFields in VC1. Then I set myself as the delegate of VC2, pass VC2 the dictionary with the input data and segue to VC2. In VC2 I fill in another 4 textFields and add these to the dictionary. If I then decide I need to change something in VC1 I tap the back button and amend the data. But when I go forwards again I lose the stuff I input on VC2.
How do I pass the dictionary back to VC1 with the added info so that when it gets passed forwards to VC2 again it has everything in it?
The delegate (VC1) has a method to update its dictionary with the dictionary in VC2.
I have also customised the backBarButtonItem in VC2 by setting it in the prepareForSegue: method in VC1.
I think I'm getting close but...
I can only get the target actions to work by setting a leftBarButtonItem in VC2 and using that instead of the default back button.
Setting the back button in VC1 (prepareForSegue:) doesn't seem to allow any target or action to be set.
I know I can't set the back button in VC2, so what can I do? Can I set the target and action of the back button from VC2 using the delegate?
I think it may be something to do with UINavigationBarDelegate but I can't figure out where to put what with that. I tried setting it up in VC2 but it didn't do anything.
TIA.
Here's the relevant code:
Protocol:
#import <Foundation/Foundation.h>
#protocol IAXAddNewUserDelegate <NSObject>
#required
- (void)updateNewUserDataWithData: (NSMutableDictionary *)newData;
#end
From VC1.h:
#import "IAXAddNewUserDelegate.h"
#interface IAXAddNewUser1 : UITableViewController <UITextFieldDelegate, UIAlertViewDelegate, IAXAddNewUserDelegate>
#property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#property (strong, nonatomic) User *selectedUser;
#property (strong, nonatomic) User *aNewUser;
#property BOOL isFirstUser;
- (void)updateNewUserDataWithData: (NSMutableDictionary *)newData;
#end
From VC1.m:
#pragma mark - Segues
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"AddUser2"]) {
IAXAddNewUser2 *addUser2VC = segue.destinationViewController;
addUser2VC.managedObjectContext = self.managedObjectContext;
addUser2VC.progressTotal = self.progressTotal;
addUser2VC.isFirstUser = self.isFirstUser;
addUser2VC.userData = self.userData;
addUser2VC.delegate = self;
if (self.selectedUser) {
addUser2VC.selectedUser = self.selectedUser;
}
self.title = #"Step 1";
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:#"Back"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(passDataBack:)];
self.navigationItem.backBarButtonItem = backButton;
}
}
#pragma mark - IAXAddNewUserDelegate Methods
- (void)updateNewUserDataWithData: (NSMutableDictionary *)newData
{
self.userData = newData;
NSLog(#"Updated AddUserVC1");
}
From VC2.m
-(void)passDataBack:(id)sender
{
NSLog(#"Sending Data Back to VC1");
[self.delegate updateNewUserDataWithData:self.userData];
[self.navigationController popViewControllerAnimated:YES];
}
If you're updating all the dictionaries from all the other dictionaries, try using a singleton. You can see an example here: https://stackoverflow.com/a/9690731/542400
Also, here's some code:
MainDictionary.h
#interface MainDictionary : NSObject{
NSMutableDictionary *dictionary;
}
+(MainDictionary *)sharedDictionary;
-(NSString *)getStringForKey:(NSString *)string;
-(void)setString:(NSString *)string forKey:(NSString *)key;
#end
MainDictionary.m
#import "MainDictionary.h"
static MainDictionary *sharedDictionary;
#implementation MainDictionary
-(id)init{
self = [super init];
dictionary = [[NSMutableDictionary alloc] init];
// if you want to add anything preliminary to the dictionary, do it here
return self;
}
+(MainDictionary *)sharedDictionary{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedDictionary = [[self alloc] init];
});
return sharedDictionary;
}
-(NSString *)getStringForKey:(NSString *)string{
return [dictionary objectForKey:string];
}
-(void)setString:(NSString *)string forKey:(NSString *)key{
[dictionary setValue:string forKey:key];
}
#end
Now #import MainDictionary.h, and any time you want to access or set values in that dictionary (in this example, when your textFields end editing), just do this:
-(void)textFieldDidEndEditing:(UITextField *)textField{
if(textField == textField1){
[[MainDictionary sharedDictionary] setString: textField.text forKey:#"textField1"];
}
}
or:
-(void)viewWillAppear{
textField1.text = [[MainDictionary sharedDictionary] getStringForKey:#"textField1"];
[super viewWillAppear:YES];
}
Implement this in each VC, and you're good to go.

XCode: Displaying a UIDatePicker when user clicks on UITextbox

I have already researched this topic to death and found people posting the exact same question on a number of websites including right here in stackoverflow.
I have tried all of the suggestions but have been unable to get the UIDatePicker to actually display. It doesn't seem to matter what approach I take. I've tried using the inheritance model where I subclass the UITextBox control and override it's default methods in order to display the UIDatePicker and then I make sure that in StoryBoard I set the class of my UITextView control to be that custom class. I've tried programmatically generating the UIDatePicker and also tried dragging it onto the view in StoryBoard. When I try the programmatic approach nothing is displayed and when I try dragging it onto the StoryBoard it ALWAYS displays. When I set it's attribute to "hidden" it hides but then I can't get it to show even when I try to add code to the textboxDidBeginEditing method that should unhide it.
I've made sure to set the UITextView's inputView property equal to my UIDatePicker control.
Nothing works! I don't understand why Apple didn't just make the UIDatePicker one of the default options in the drop down list in the Attributes Inspector for the UITextView control. That would have made this so much easier.
Below is some of the code from my implementation class file.
#import "AddTasksViewController.h"
#implementation AddTasksViewController
#synthesize dueDate;
#synthesize description;
#synthesize shortTitle;
#synthesize datePicker;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
self.dueDate.inputView = datePicker;
}
return self;
}
- (IBAction)dueDateDidBeginEditing:(UITextView *)textField
{
[textField resignFirstResponder];
[datePicker setFrame:CGRectMake(0,200,320,120)];
[datePicker addTarget:self action:#selector(done) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:datePicker];
}
Here is what my header file looks like...
#import <UIKit/UIKit.h>
#interface AddTasksViewController : UIViewController
#property (nonatomic, copy) IBOutlet UITextView *dueDate;
#property (nonatomic, copy) IBOutlet UITextView *description;
#property (nonatomic, copy) IBOutlet UITextView *shortTitle;
#property (nonatomic, retain) IBOutlet UIDatePicker *datePicker;
- (IBAction)doneEditing:(id)sender;
- (IBAction)dateChanged:(id)sender;
- (IBAction)dueDateDidBeginEditing:(UITextView *)textField;
#end
As I've already mentioned, the other approach that I took (i.e. subclassing UITextView) didn't work either. I copied the code provided here exactly as it was show. I then added the custom classes called "DateField" to my project (both the header and implementation files) and then replaced the UITextBox declaration for the dueDate with DateField in both my AddTaskViewController.h and AddTaskViewController.m files and made sure that the StoryBoard references were updated to by selecting DateField for the control's class in the Identity Inspector.
No matter what I do I cannot get the UIDatePicker to display upon clicking on the UITextView. When I set a breakpoint it does hit the dueDateDidBeginEditing method so I know that something is being triggered. The problem is that I don't understand why a subView is not being showing with the UIDatePicker.
Any help would be greatly appreciated as this seemingly straightforward task seems to be taking much, much longer than it should. I could do this sort of stuff with my eyes closed and hands tied behind my back in Java and C# yet everything is so unnecessarily complicated when it comes to Objective-C. The syntax really irritates me.
So many square brackets!!! Arghhhh!!!
Showing a UIDatePicker for the inputView of a UITextField is relatively hard compared to showing a keyboard, but relatively easy compared to the trouble you've had.
One of the first problems I noticed with your code, and it's a very common problem with those new to iOS/Mac development, is that you are attempting to set the property of an object that doesn't exist yet. Putting "self.dueDate.inputView = datePicker;" in your initWithNibName:bundle: will not work because the view has not yet loaded, and dueDate is part of your view. In objective-c an object is instantiated with alloc & init. Init is the first real method call to any object. At this point in your view controller's life the view has not been created yet. The method call where self.dueDate.inputView = datePicker; belongs is in the viewDidLoad method. It is called exactly when it sounds like it's called, and your dueDate property will be properly loaded at that point. There is no need to use a custom subclass of UITextField to display a date picking view for for your text field. Here is a very basic example of a custom input view class:
ExampleBasicDateInputView.h:
#import <UIKit/UIKit.h>
#interface ExampleBasicDateInputView : UIView
#property (strong,nonatomic) UIDatePicker *datePicker;
#end
ExampleBasicDateInputView.m:
#import "ExampleBasicDateInputView.h"
#implementation ExampleBasicDateInputView{
UITextField *_inputField; // ivar to store the textfield currently being edited
}
#synthesize datePicker = _datePicker;
// TARGET METHODS
-(void)pickerValueChanged:(UIDatePicker *)picker{
_inputField.text = self.datePicker.date.description; // set text to date description
}
-(void)viewDoubleTapped:(UITapGestureRecognizer *)tapGR{
[_inputField resignFirstResponder]; // upon double-tap dismiss picker
}
-(void)textFieldBeganEditing:(NSNotification *)note{
_inputField = note.object; // set ivar to current first responder
}
-(void)textFieldEndedEditing:(NSNotification *)note{
_inputField = nil; // the first responder ended editing CRITICAL:avoids retain cycle
}
// INITI METHODS
-(void)initializationCodeMethod{
_datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 0, 320, 0)];// All pickers have preset height
self.bounds = _datePicker.frame; // Make our view same size as picker
[self addSubview:_datePicker];
[_datePicker addTarget:self action:#selector(pickerValueChanged:) forControlEvents:UIControlEventValueChanged]; // register to be notified when the value changes
// As an example we'll use a tap gesture recognizer to dismiss on a double-tap
UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(viewDoubleTapped:)];
tapGR.numberOfTapsRequired = 2; // Limit to double-taps
[self addGestureRecognizer:tapGR];
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:#selector(textFieldBeganEditing:) name:UITextFieldTextDidBeginEditingNotification object:nil]; // Ask to be informed when any textfield begins editing
[center addObserver:self selector:#selector(textFieldEndedEditing:) name:UITextFieldTextDidEndEditingNotification object:nil]; // Ask to be informed when any textfield ends editing
}
-(id)init{
if ((self = [super init])){
[self initializationCodeMethod];
}
return self;
}
-(id)initWithFrame:(CGRect)frame{
if ((self = [super initWithFrame:frame])){
[self initializationCodeMethod];
}
return self;
}
-(id)initWithCoder:(NSCoder *)aDecoder{
if ((self = [super initWithCoder:aDecoder])){
[self initializationCodeMethod];
}
return self;
}
-(void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidBeginEditingNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidEndEditingNotification object:nil];
}
#end
Then in view did load you would use this class like this:
ExampleBasicDateInputView *dateEntryView = [[ExampleBasicDateInputView alloc] init];
self.dueDate.inputView = datePickerView;
And as you see in the .h file we've exposed the date picker instance as a property so you can set the style. etc. like so:
dateEntryView.datePicker.datePickerMode = UIDatePickerModeDate;
Obviously this is a very basic example, but I think it shows what can be done.
I had the same issue using Storyboard. Here is how I resolved it:
Overview:
I alloc and initialize my UIDatePicker property in viewDidLoad:. I then set the inputView property of my textfield to my datepicker property.
Here is my code:
In TripViewController.h:
#property (nonatomic,strong) IBOutlet UIDatePicker *datePicker;
In TripViewController.m:
#synthesize datePicker;
...
-(void)viewDidLoad {
...
self.datePicker = [[UIDatePicker alloc]init];
[self.datePicker addTarget:self action:#selector(dateChanged) forControlEvents:UIControlEventValueChanged];
self.dateField.inputView = self.datePicker;
}
I then implement my method, dateChanged so that whenever the date picker wheel stops moving, my textfield is updated.
- (void)dateChanged
{
NSDate *date = self.datePicker.date;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateStyle:NSDateFormatterMediumStyle];
self.dateField.text = [dateFormat stringFromDate:date];
}
add UITextField's delegate in .h file to call this function when touched. then use the text field's tag value to determine what you want to do when the field is selected.
-(BOOL) textFieldShouldBeginEditing:(UITextField *) textField
{
activeTextField = textField;
if (textField.tag == 1)
{
self.datePicker.datePickerMode = UIDatePickerModeDate;
self.isDatePicker = TRUE;
self.tempTextField = textField;
[self showPicker];
return NO;
}
else if (textField.tag == 2)
{
self.datePicker.datePickerMode = UIDatePickerModeTime;
self.isDatePicker = TRUE;
self.tempTextField = textField;
[self showPicker];
return NO;
}
else if (textField.tag == 3)
{
self.isDatePicker = FALSE;
self.tempTextField = textField;
[self showPicker];
return NO;
}
else
{
self.tempTextField = textField;
return YES;
}
}
It is very easy. Defines delegate TextField (UITextFieldDelegate) in the .h in the viewDidLoad .m
myTextField.setDelegate = self;
In the same viewDidLoad associates the datePicker to myTextField.
myTextField.inputView = myDatePicker;
You can also do anime, but this is the easiest way.

Present view from delegate modally in iOS 5

I cannot seem to find this anywhere online. I have an add button in one of my views and I have hooked it up to an IBAction method called add. In my storyboard, I have created a view that has a form all set up on it. I have assigned a class to that view in the storyboard as well. That class is called AddItemViewController.
I am trying to present this view modally and then set the delegate to the view that called the AddItemViewController. However, all I get is an empty UITableViewController that shows up. Here is my code that I'm trying to use:
- (IBAction)add {
AddItemViewController *addItem = [[AddItemViewController alloc] init];
addItem.delegate = self;
[self presentModalViewController:addItem animated:YES];
}
Is there anything I'm missing? Why does it just show an empty table and not the view controller that I set up in the storyboard?
Here is the code from the AddItemViewController:
#interface AddItemViewController : UITableViewController <UITextFieldDelegate> {
}
#property (strong, nonatomic) IBOutlet UITextField *note;
- (void)save:(id)sender;
- (void)cancel:(id)sender;
#end
#implementation AddItemViewController
- (void)viewDidLoad {
}
- (IBAction)cancel:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)save:(id)sender {
DbHandler *db = [[DbHandler alloc] init];
[db executeUpdate:self.note];
[self dismissViewControllerAnimated:YES completion:nil];
}
#end
Well, AddItemViewController inherits from UITableViewController, not UIViewController, so it makes sense that a UITableViewController is showing up.
You should initiate the AddItemViewController like this:
AddItemViewController *addItem = [[AddItemViewController alloc] initWithNibName:#"AddItemViewController"];