I have UIViewController with UIDatePicker inside. I connect UIDatePicker with IBOutlet property in header class, because I'm using storyboards in my app:
#import <UIKit/UIKit.h>
#protocol CreationDateDelegate <NSObject>
#optional
-(void)selectedDateIs:(NSString*)dateValue;
#end
#interface SelectCreationDateViewController : UIViewController
{
IBOutlet UIDatePicker *datePicker;
}
#property (nonatomic,assign)id<CreationDateDelegate>creationDateDelegate;
#property (nonatomic,retain) IBOutlet UIDatePicker *datePicker;
#end
--- .m -----
#import "SelectCreationDateViewController.h"
#interface SelectCreationDateViewController ()
{
NSString *dateFromString;
}
#end
#implementation SelectCreationDateViewController
#synthesize creationDateDelegate,datePicker;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
}
return self;
}
- (void)viewDidLoad
{
self.title = #"Select creation date";
[super viewDidLoad];
[datePicker setHidden:NO];
datePicker.timeZone = [NSTimeZone localTimeZone];
[datePicker setDatePickerMode:UIDatePickerModeDate];
[datePicker addTarget:self action:#selector(changeValueOfDatePicker:) forControlEvents:UIControlEventValueChanged];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)viewWillDisappear:(BOOL)animated{
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
NSString *dateFromString = [formatter stringFromDate:datePicker.date];
[self.creationDateDelegate selectedDateIs:dateFromString];
}
-(void)changeValueOfDatePicker:(id)sender{
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
dateFromString = [formatter stringFromDate:datePicker.date];
[self.creationDateDelegate selectedDateIs:dateFromString];
NSLog(#"Date from string value equal %#",dateFromString);
}
#end
Why every time when I change the value of the DatePicker returned value does not change? Any ideas? Also, let me know if I am making any mistake in the code.
Set some dateformate also
-(void)changeValueOfDatePicker:(id)sender{
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm"];
dateFromString = [formatter stringFromDate:datePicker.date];
[self.creationDateDelegate selectedDateIs:dateFromString];
NSLog(#"Date from string value equal %#",dateFromString);
}
Fix it by adding this line of code,
only if you are using iOS7
- in method (void)viewDidLoad method
[self.datePicker setDate:[NSDate date] animated:YES];
Related
Hi all i am working with FSCalandar in my project. Everything is working fine but i am not able change calendar date color for the date which will entered by user. Basically i want to add the functionality of present and absent in my project using FSCalander. i already called fscalanderappearance delegate method.Please look at my code.
This is .h file
#interface CalTableCellTableViewCell : UITableViewCell <FSCalendarDelegate, FSCalendarDataSource, FSCalendarDelegateAppearance>
{
NSDate *myDate;
NSDate *EndDate;
NSMutableArray *array;
}
#property (weak , nonatomic) FSCalendar *calendar;
#property (weak, nonatomic) IBOutlet NSLayoutConstraint *calendarHeightConstraint;
#property (weak, nonatomic) IBOutlet UIView *calview;
#property (strong, nonatomic) NSDate *selectedDate;
#property (strong, nonatomic) NSDictionary *fillSelectionColors;
#property (strong, nonatomic) NSDictionary *fillDefaultColors;
#property (strong, nonatomic) NSDictionary *borderDefaultColors;
#property (strong, nonatomic) NSDictionary *borderSelectionColors0;
#property (strong, nonatomic) NSArray *datesWithEvent;
#property (strong, nonatomic) NSArray *datesWithMultipleEvents;
#end
This is .m file.
#import "CalTableCellTableViewCell.h"
#implementation CalTableCellTableViewCell
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
myDate = (NSDate *)[[NSUserDefaults standardUserDefaults] objectForKey:#"myDateKey"];
NSLog(#"mydate %#", myDate);
EndDate = (NSDate *)[[NSUserDefaults standardUserDefaults] objectForKey:#"EndDateKey"];
FSCalendar *calendar = [[FSCalendar alloc] initWithFrame:CGRectMake(0, 0, 250, 150)];
calendar.dataSource = self;
calendar.delegate = self;
[self.contentView addSubview:calendar];
self.calendar = calendar;
_calendar.scrollDirection = FSCalendarScrollDirectionVertical;
calendar.appearance.caseOptions = FSCalendarCaseOptionsHeaderUsesUpperCase|FSCalendarCaseOptionsWeekdayUsesSingleUpperCase;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"d.M.yyyy";
NSString *string = [formatter stringFromDate:[NSDate date]];
NSLog(#"current date %#", string);
_calendar.appearance.selectionColor = [UIColor blueColor];
_calendar.appearance.todayColor = [UIColor greenColor];
_calendar.appearance.cellShape = FSCalendarCellStyleRectangle;
NSUserDefaults *userDef = [NSUserDefaults standardUserDefaults];
NSArray *testarray = [userDef objectForKey:#"name"];
array = [[NSMutableArray alloc]initWithArray:testarray];
NSLog(#"arraydata %#", array);
self.datesWithEvent = #[#"2016-09-03",
#"2015-10-06",
#"2015-10-12",
#"2015-10-25"];
self.datesWithMultipleEvents = #[#"2015-10-08",
#"2015-10-16",
#"2015-10-20",
#"2015-10-28"];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)calendar:(FSCalendar *)calendar boundingRectWillChange:(CGRect)bounds animated:(BOOL)animated
{
_calendarHeightConstraint.constant = CGRectGetHeight(bounds);
[self.contentView layoutIfNeeded];
}
- (NSDate *)minimumDateForCalendar:(FSCalendar *)calendar
{
return myDate;
}
- (NSDate *)maximumDateForCalendar:(FSCalendar *)calendar
{
return EndDate;
}
#pragma mark - <FSCalendarDelegateAppearance>
- ( UIColor *)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance titleDefaultColorForDate:(NSDate *)date;
{
NSString *datestring = [calendar stringFromDate:myDate format:#"yyyy-MM-dd"];
if ([_datesWithEvent containsObject:datestring]) {
NSLog(#"test");
return calendar.appearance.borderDefaultColor = [UIColor redColor];
}
else if ([_datesWithMultipleEvents containsObject:datestring])
{
NSLog(#"testing");
}
return nil;
}
Please help if anyone go with this problem. thanks. Delegates method not called.
You can apply FSCalendar Data, Delegate & FSCalendarDelegateAppearance to the TableViewController or to the ViewController that contains TableView instead of implementing it in UITableViewCell. Then override the method titleDefaultColorForDate as shown below. It works for me.
-(UIColor *)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance titleDefaultColorForDate:(NSDate *)date{
self.formatter = [[NSDateFormatter alloc] init];
self.formatter.dateFormat = #"yyyy/MM/dd";
NSString *CurrentDate = [self.formatter stringFromDate:date];
NSString *Today = [self.formatter stringFromDate:[_Calendar today]];
//_bookedDates are array of specific dates
if([_bookedDates containsObject:CurrentDate])
//if booking dates contains currentdate change the color of the title
return [UIColor whiteColor];
else
return appearance.titlePlaceholderColor;
}
My main storyboard has a stopwatch. I can start the watch, and then navigate to another storyboard. When I return to the main stopwatch storyboard it has stopped and reset to zero. Please help me figure out how to keep the stopwatch going forever until I press STOP. Thanks
All storyboards have same controller
here is the .h
#import <UIKit/UIKit.h>
#interface MainViewController : UIViewController{
UILabel *lbl;
NSTimer *stopTimer;
NSDate *startDate;
BOOL running;
}
#property (weak, nonatomic) IBOutlet UIBarButtonItem *sidebarButton;
#property (strong,nonatomic) IBOutlet UILabel *lbl;
-(IBAction)startPressed:(id)sender;
-(IBAction)resetPressed:(id)sender;
-(void)updateTimer;
#end
here is the .m
#import "MainViewController.h"
#import "SWRevealViewController.h"
#interface MainViewController ()
#end
#implementation MainViewController
#synthesize lbl;
- (void)viewDidLoad
//stopwatch open
{
[super viewDidLoad];
lbl.text = #"00.00.00.000";
running = FALSE;
startDate = [NSDate date];
//stopwatch close
[super viewDidLoad];
self.title = #"therapyTools";
// Change button color
_sidebarButton.tintColor = [UIColor colorWithWhite:0.1f alpha:0.9f];
// Set the side bar button action. When it's tapped, it'll show up the sidebar.
_sidebarButton.target = self.revealViewController;
_sidebarButton.action = #selector(revealToggle:);
// Set the gesture
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//stopwatch open
-(IBAction)startPressed:(id)sender{
if(!running){
running = TRUE;
[sender setTitle:#"STOP" forState:UIControlStateNormal];
if (stopTimer == nil) {
stopTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0
target:self
selector:#selector(updateTimer)
userInfo:nil
repeats:YES];
}
}else{
running = FALSE;
[sender setTitle:#"START" forState:UIControlStateNormal];
[stopTimer invalidate];
stopTimer = nil;
}
}
-(void)updateTimer{
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm:ss.SSS"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString=[dateFormatter stringFromDate:timerDate];
lbl.text = timeString;
}
-(IBAction)resetPressed:(id)sender{
[stopTimer invalidate];
stopTimer = nil;
startDate = [NSDate date];
lbl.text = #"00.00.00.000";
running = FALSE;
}
//stopwatch close
#end
this is my first post on stackoverflow so i'll try to be as much clear as possible.
I'm a very beginner in iPhone developing so please excuse by advance if my question is a noob one.
Please excuse my english also...
I'm trying to show in some UITextLabel the date values immediately when UIViewController shows up.
But the dateLabel and hourLabel don't update. The code is executing well only if i put a breakpoint just after the super initialization.
Calling the UIViewController CustomDatePicker
- (IBAction)setStartPointClicked:(id)sender {
_picker = [[CustomDatePicker alloc]initWithNibName:#"CustomDatePicker" bundle:nil];
_picker.delegate = self;
[self presentViewController:_picker animated:YES completion:^{
}] ;
}
iniWithNibName method called to initialize the controller
- (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if(!self) { //<=============Breakpoint
return nil;
}
[self.datePicker addTarget:self action:#selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd/MM/yyyy"];
NSString* str = [dateFormatter stringFromDate:_datePicker.date];
[_dateLabel setText:str];
NSLog(str);
[dateFormatter setDateFormat:#"HH:mm"];
str = [dateFormatter stringFromDate:_datePicker.date];
[_hourLabel setText:str];
NSLog(str);
return self;
}
I think i'm trying to call properties before that they have the time to be assigned. If I put the breakpoint after each label string change it doesn't update. They are executing only if the breakpoint is placed beetween the super init and the code to execute. Does breakpoint is giving some time to my application to load objects?
Any ideas?
Thanks by advance
Put your code into viewDidLoad instead.
Please try the following changes:
// The init... method. This is the iOS standard way of writing it
- (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if(self) {
}
return self;
}
// viewDidLoad method
-(void)viewDidLoad {
[self.datePicker addTarget:self action:#selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd/MM/yyyy"];
NSString* str = [dateFormatter stringFromDate:self.datePicker.date];
[self.dateLabel setText:str];
NSLog(str);
[dateFormatter setDateFormat:#"HH:mm"];
str = [dateFormatter stringFromDate:_datePicker.date];
[self.hourLabel setText:str];
NSLog(str);
}
Hope this helps!
I'm parsing some information to my app using JSON. I'm able to show the formattedDate on my Main View Controller but when I want to do it on my destinationView page (UpcomingReleaseViewController), I get a "null" string. This is what I have so far:
UpcomingRelease.h
#property (nonatomic, strong) NSString *release_date;
- (NSString *) formattedDate;
UpcomingRelease.m
- (NSString *) formattedDate {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *tempDate = [dateFormatter dateFromString:self.release_date];
[dateFormatter setDateFormat:#"EE MMM,dd"];
return [dateFormatter stringFromDate:tempDate];
}
UpcomingReleaseViewController.h
#property (strong, nonatomic) UpcomingRelease *singleRelease;
#property (weak, nonatomic) IBOutlet UILabel *release_date;
UpcomingReleaseViewController.m
#synthesize singleRelease = _singleRelease;
#synthesize release_date = _release_date;
- (void)viewDidLoad
{
[super viewDidLoad];
self.release_date.text = [NSString stringWithFormat:#"%#", _singleRelease.formattedDate];
}
JSON
release_date: "2013-09-28T00:00:00.000Z"
Thanks.
In UpcomingRelease.m you need to parse the date's 'T' and 'Z' as literal characters and account for the fractional seconds:
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
I are trying to make to a stopwatch app and facing problems getting it to work properly. When I start the stopwatch and stop and start off again, it doesn't continue from where it left off. It carries on running as if it didn't stop. Need some guidance on getting it work properly. I have been trying since morning, the rest of the functions i have made as similar to the apple's stopwatch, only this is bugging me.. Appreciate any help...
The code looks like this:
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>{
UILabel *lbl;
NSTimer *stopTimer;
NSDate *startDate,*currentDate;
BOOL running;
UIButton *bttn;
NSMutableArray *tableItems;
NSString *timeString,*currentString;
UITableView *tableview;
int counter;
}
#property (strong,nonatomic) IBOutlet UILabel *lbl;
#property (strong,nonatomic) IBOutlet UIButton *bttn;
#property (strong,nonatomic) NSMutableArray *tableItems;
#property (strong,nonatomic) NSString *timeString;
#property (strong,nonatomic) IBOutlet UITableView *tableview;
-(IBAction)startPressed:(id)sender;
-(IBAction)resetPressed:(id)sender;
-(void)updateTimer;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize lbl,bttn,tableItems,timeString,tableview;
- (void)viewDidLoad
{
[super viewDidLoad];
lbl.text = #"00.00.00.0";
running = FALSE;
//difference = #"0";
startDate = [NSDate date];
tableItems = [[NSMutableArray alloc] init];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)startPressed:(id)sender{
if(!running){
running = TRUE;
[sender setTitle:#"Stop" forState:UIControlStateNormal];
[bttn setTitle:#"Lap" forState:UIControlStateNormal];
if (stopTimer == nil) {
stopTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0
target:self
selector:#selector(updateTimer)
userInfo:nil
repeats:YES];
}
}else{
running = FALSE;
//startDate = currentDate;
//difference = currentString;
[sender setTitle:#"Start" forState:UIControlStateNormal];
[bttn setTitle:#"Restart" forState:UIControlStateNormal];
[stopTimer invalidate];
stopTimer = nil;
}
}
-(void)updateTimer{
currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm:ss.S"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
timeString=[dateFormatter stringFromDate:timerDate];
lbl.text = timeString;
}
-(IBAction)resetPressed:(id)sender{
if (!running) {
[stopTimer invalidate];
stopTimer = nil;
tableItems = [[NSMutableArray alloc] init];
startDate = [NSDate date];
lbl.text = #"00.00.00.0";
running = FALSE;
}
else{
[tableItems insertObject:timeString atIndex:0];
[tableview reloadData];
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return tableItems.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//Step 1:Check whether if we can reuse a cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
//Step2: If there are no new cells to reuse,create a new one
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:#"cell"];
}
//Step 3: Set the cell text content
cell.textLabel.text = [tableItems objectAtIndex:indexPath.row];
//Step 4: Return the row
return cell;
}
#end
In your updateTimer method you calculate the time difference between startDate and the current date. You don't take into account that you would have to subtract the time that passed while the stopwatch was stopped.
Edit:
I'd suggest to sum up and save all timeIntervals that pass between start and stop
Add a property NSTimeInterval timePassed to your class and modify your code like this:
- (void)viewDidLoad
{
//...
timePassed = 0;
}
-(IBAction)startPressed:(id)sender{
if(!running){
//...
startDate = [NSDate date];
//...
}else{
NSDate *currentDate = [NSDate date];
NSTimeInterval intervalToAdd = [currentDate timeIntervalSinceDate:startDate];
timePassed += intervalToAdd;
//...
}
-(void)updateTimer{
currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
timeInterval += timePassed; // <<<<<
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm:ss.S"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
timeString=[dateFormatter stringFromDate:timerDate];
lbl.text = timeString;
}
-(IBAction)resetPressed:(id)sender{
if (!running) {
//...
timePassed = 0;
//...
}
//...
}
Quoting some code inside my active project.
NSDate *timeStart = [NSDate dateWithTimeIntervalSince1970:0];
NSDate *timeEnd = [timeStart dateByAddingTimeInterval:_timePassed];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"00:00:00"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"GMT"]];
NSString *strDate = [dateFormatter stringFromDate:timeEnd];
_timeLabel.text = strDate;
This is how I did mine. If you want to use UILabel as a stopwatch, MZTimerLabel is a awesome two line solution for you. Take a look.
Cheers.