How to modify selected UITexFiled value in Array of Textfield - ios

Currently, I created Array of UITextField based on Response from Server in my UI, My response contains three types of response in single API, i.e I get 5 key and Values. Values contains Types like String, Date, Array, based on this when I select the UITextFiled the value must change according to that Particular TextFiled
Here my Sample Code:
for (int i=0;i<itemAttributeArray.count;i++){
UIColor *floatingLabelColor = [UIColor brownColor];
textField1 = [[JVFloatLabeledTextField alloc] initWithFrame:CGRectMake(16, y, width, height)];
textField1.delegate = self;
//Set tag 101
textField1.tag = 101;
NSLog(#"textField1.tag - %ld",(long)textField1.tag);
textField1.text = [[itemAttributeArray valueForKey:#"value"]objectAtIndex:i];
[self SetTextFieldBorder:textField1];
textField1.placeholder = [keyArr objectAtIndex:i];
textField1.font = [UIFont systemFontOfSize:kJVFieldFontSize];
// textField1.clearsOnBeginEditing = YES;
textField1.clearButtonMode = UITextFieldViewModeWhileEditing;
textField1.floatingLabelFont = [UIFont boldSystemFontOfSize:kJVFieldFloatingLabelFontSize];
textField1.floatingLabelTextColor = floatingLabelColor;
// textField1.translatesAutoresizingMaskIntoConstraints = NO;
[textField1 resignFirstResponder];
[_scroll addSubview:textField1];
[textFields addObject:textField1];
[textField1 release];
y += height + margin;
if ([[[itemAttributeArray valueForKey:#"type"] objectAtIndex:i] isEqualToString:#"string"]){
NSLog(#"type - %#",[[itemAttributeArray valueForKey:#"type"] objectAtIndex:i]);
}else if ([[[itemAttributeArray valueForKey:#"type"]
objectAtIndex:i] isEqualToString:#"date"]){
NSLog(#"type - %#",[[itemAttributeArray valueForKey:#"type"] objectAtIndex:i]);
textField1.tag = 102;
[textField1 addTarget:self action:#selector(textFieldDidChange_dateChek)
forControlEvents:UIControlEventEditingDidBegin];
}else if ([[[itemAttributeArray valueForKey:#"type"] objectAtIndex:i] isEqualToString:#"double"]){
NSLog(#"type - %#",[[itemAttributeArray valueForKey:#"type"] objectAtIndex:i]);
}
-(void)textFieldDidChange_dateChek{
NSLog(#"iam called on first edit");
_picker_uiView.hidden = false;
[_datePickerView addTarget:self action:#selector(datePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
}
- (void)datePickerValueChanged:(id)sender {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"h:mm a"];
textField1.text = [dateFormatter
stringFromDate:_datePickerView.date];
}
When I select the date value is entered in the last object to UITextfield but I selected index is 2nd but values changing on the last element of UITextfield

you are create the textfield in globally, thats the reason you get the last index only. in here assign the tag for each textfield as well as create the instance value.for e.g
for (int i=0;i<itemAttributeArray.count;i++){
UIColor *floatingLabelColor = [UIColor brownColor];
JVFloatLabeledTextField *textField1 = [[JVFloatLabeledTextField alloc] initWithFrame:CGRectMake(16, y, width, height)];
textField1.delegate = self;
//Set tag 101
textField1.tag = 101 + i;
NSLog(#"textField1.tag - %ld",(long)textField1.tag);
textField1.text = [[itemAttributeArray valueForKey:#"value"]objectAtIndex:i];
[self SetTextFieldBorder:textField1];
textField1.placeholder = [keyArr objectAtIndex:i];
textField1.font = [UIFont systemFontOfSize:kJVFieldFontSize];
// textField1.clearsOnBeginEditing = YES;
textField1.clearButtonMode = UITextFieldViewModeWhileEditing;
textField1.floatingLabelFont = [UIFont boldSystemFontOfSize:kJVFieldFloatingLabelFontSize];
textField1.floatingLabelTextColor = floatingLabelColor;
// textField1.translatesAutoresizingMaskIntoConstraints = NO;
[textField1 resignFirstResponder];
[_scroll addSubview:textField1];
[textFields addObject:textField1];
[textField1 release];
y += height + margin;
if ([[[itemAttributeArray valueForKey:#"type"] objectAtIndex:i] isEqualToString:#"string"]){
NSLog(#"type - %#",[[itemAttributeArray valueForKey:#"type"] objectAtIndex:i]);
}else if ([[[itemAttributeArray valueForKey:#"type"] objectAtIndex:i] isEqualToString:#"date"]){
NSLog(#"type - %#",[[itemAttributeArray valueForKey:#"type"] objectAtIndex:i]);
[textField1 addTarget:self action:#selector(textFieldDidChange_dateChek:)
forControlEvents:UIControlEventEditingDidBegin];
}else if ([[[itemAttributeArray valueForKey:#"type"] objectAtIndex:i] isEqualToString:#"double"]){
}
}
and handle the textfield action
-(void)textFieldDidChange_dateChek:(JVFloatLabeledTextField*)textfield{
NSLog(#"iam called on first edit");
_picker_uiView.hidden = false;
_datePickerView.tag = textfield.tag;
[textfield resignFirstResponder];
[_datePickerView addTarget:self action:#selector(datePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
textfield.inputView = _datePickerView;
}
finally assign the value to the textfield as like follow
- (void)datePickerValueChanged:(UIDatePicker*)sender {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"h:mm a"];
// textField1.tag = 102;
for(id aSubView in [_scroll subviews]){
if([aSubView isKindOfClass:[JVFloatLabeledTextField class]])
{
JVFloatLabeledTextField *textFds=(JVFloatLabeledTextField*)aSubView;
if (textFds.tag == sender.tag) {
NSLog(#"dad == %#",[dateFormatter stringFromDate:sender.date]);
textFds.text = [dateFormatter stringFromDate:sender.date];
[textFds resignFirstResponder];
[sender removeFromSuperview];
break;
}
}
}
}

Related

Create Dynamic textField

I am developing IOS App. I Create TextField and Button Dynamically and Set tag value.but problem is that when click button to get textfield first index value that show null. only last index value of textfield i am get not for other What is the problem. Thanks in Advance.
Code..
- (void)addfields{
_field = [[UITextField alloc]initWithFrame:CGRectMake(5.0f, 5.0f, 195.0f, 30.0f)];
_field.layer.borderColor=[[UIColor colorWithRed:211.0f/255.0f
green:211.0f/255.0f
blue:211.0f/255.0f
alpha:1.0] CGColor];
[_field.layer setBorderWidth: 1.0];
//_field.tag = count;
[_filterPossibleValueView addSubview:_field];
_addField = [[UIButton alloc]initWithFrame:CGRectMake(202.0f, 5.0f, 30.0f, 30.0f)];
_addField.backgroundColor = [UIColor blackColor];
//_addField.tag = count;
[_addField addTarget:self action:#selector(customFieldAdd:) forControlEvents:UIControlEventTouchUpInside];
[_filterPossibleValueView addSubview:_addField];
}
- (IBAction)customFieldAdd:(id)sender{
[_addfieldArray addObject:_field];
[_scroller setScrollEnabled:YES];
_scroller.contentSize=CGSizeMake(240.0f, _field.frame.size.height+x+50);
[_copyfield removeFromSuperview];
[copyAddButton removeFromSuperview];
x = 10;
y = 10;
for( int i = 0; i < [_addfieldArray count]; i++ ) {
_copyfield = [[UITextField alloc]initWithFrame:CGRectMake(5.0, x + _field.frame.size.height, 195.0f, 30.0f)];
_copyfield.layer.borderColor=[[UIColor colorWithRed:211.0f/255.0f
green:211.0f/255.0f
blue:211.0f/255.0f
alpha:1.0] CGColor];
_copyfield.tag = i;
[_copyfield.layer setBorderWidth: 1.0];
[_filterPossibleValueView addSubview:_copyfield];
x = x+_field.frame.size.height+10;
copyAddButton = [[UIButton alloc]initWithFrame:CGRectMake(202.0f, y + _addField.frame.size.height, 30.0f, 30.0f)];
copyAddButton.backgroundColor = [UIColor blueColor];
copyAddButton.tag = i;
[copyAddButton addTarget:self action:#selector(customFieldDelete:) forControlEvents:UIControlEventTouchUpInside];
[_filterPossibleValueView addSubview:copyAddButton];
y = y+_addField.frame.size.height+10;
count++;
}
}
- (IBAction)customFieldDelete:(id)sender{
UIButton *button = (UIButton*)sender;
NSInteger index = button.tag;
[_addfieldArray removeObjectAtIndex:index];
// UITextField *text = (UITextField *)[_copyfield viewWithTag:index];
// NSLog(#"%ld",(long)text.tag);
UITextField *txtField = [_filterPossibleValueView viewWithTag:index];
NSLog(#"%#",txtField.text);
// [_copyfield removeFromSuperview];
// [copyAddButton removeFromSuperview];
}
I have created an sample app for dynamic fields. And getting the textfield's value on Button click. This example code will solve out your problem.
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
NSMutableArray *formArr;
NSMutableArray *txtfldArr;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
formArr = [[NSMutableArray alloc] init];
txtfldArr = [[NSMutableArray alloc] init];
UITextField *txtfld = [[UITextField alloc] init];
NSMutableDictionary *dict1 = [[NSMutableDictionary alloc] init];
[dict1 setObject:#"string" forKey:#"labelName"];
[dict1 setObject:#"name" forKey:#"labelFor"];
[dict1 setObject:#"1" forKey:#"tag"];
[dict1 setObject:txtfld forKey:#"txtFld"];
[formArr addObject:dict1];
NSMutableDictionary *dict2 = [[NSMutableDictionary alloc] init];
[dict2 setObject:#"string" forKey:#"labelName"];
[dict2 setObject:#"email" forKey:#"labelFor"];
[dict2 setObject:#"2" forKey:#"tag"];
[dict2 setObject:txtfld forKey:#"txtFld"];
[formArr addObject:dict2];
NSMutableDictionary *dict3 = [[NSMutableDictionary alloc] init];
[dict3 setObject:#"string" forKey:#"labelName"];
[dict3 setObject:#"phone" forKey:#"labelFor"];
[dict3 setObject:#"3" forKey:#"tag"];
[dict3 setObject:txtfld forKey:#"txtFld"];
[formArr addObject:dict3];
NSMutableDictionary *dict4 = [[NSMutableDictionary alloc] init];
[dict4 setObject:#"string" forKey:#"labelName"];
[dict4 setObject:#"address" forKey:#"labelFor"];
[dict4 setObject:#"4" forKey:#"tag"];
[dict4 setObject:txtfld forKey:#"txtFld"];
[formArr addObject:dict4];
int y = 70;
for (int i = 0; i < [formArr count]; i++) {
NSString *txtfldName = [NSString stringWithFormat:#"%#",[[formArr objectAtIndex:i] objectForKey:#"labelFor"]];
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(30, y+4, 80, 25)];
lbl.text = txtfldName;
lbl.textColor = [UIColor darkGrayColor];
[self.view addSubview:lbl];
UITextField *lbl_txtfld = [[UITextField alloc] initWithFrame:CGRectMake(120, y, 150, 30)];
lbl_txtfld.text = #"";
lbl_txtfld.delegate = self;
lbl_txtfld.textColor = [UIColor whiteColor];
lbl_txtfld.backgroundColor = [UIColor blackColor];
[self.view addSubview:lbl_txtfld];
[[formArr objectAtIndex:i] setObject:lbl_txtfld forKey:#"txtFld"];
y += 40;
}
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)buttonClicked:(id)sender {
for (int i = 0; i < [formArr count]; i++) {
NSString *labelName = [NSString stringWithFormat:#"%#",[[formArr
objectAtIndex:i] objectForKey:#"labelFor"]];
UITextField *txtfld = [[formArr objectAtIndex:i]
objectForKey:#"txtFld"];
NSLog(#"txtfld value for %# = %#",labelName,txtfld.text);
}
}

when i am using 3 view on viewcontroller it get slow in objective c

I am using 3 view on one UIViewController. Because of this I have lots of code in viewDidLoad() Like this:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
customActivityIndicator.animationImages = [NSArray arrayWithObjects:[UIImage imageNamed:#"tmp-0.gif"],[UIImage imageNamed:#"tmp-1.gif"],[UIImage imageNamed:#"tmp-2.gif"],[UIImage imageNamed:#"tmp-3.gif"],[UIImage imageNamed:#"tmp-4.gif"],[UIImage imageNamed:#"tmp-5.gif"],[UIImage imageNamed:#"tmp-6.gif"],[UIImage imageNamed:#"tmp-7.gif"],[UIImage imageNamed:#"tmp-8.gif"],[UIImage imageNamed:#"tmp-9.gif"],[UIImage imageNamed:#"tmp-10.gif"],[UIImage imageNamed:#"tmp-11.gif"],[UIImage imageNamed:#"tmp-12.gif"],[UIImage imageNamed:#"tmp-13.gif"],[UIImage imageNamed:#"tmp-14.gif"],[UIImage imageNamed:#"tmp-15.gif"],nil];
customActivityIndicator.animationDuration = 1.0; // in seconds
customActivityIndicator.animationRepeatCount = 0; // sets to loop
[customActivityIndicator startAnimating];
btn.hidden=YES;
UILabel *lab =[[UILabel alloc] init];
lab.text = [NSString awesomeIcon:FaMailReply];
UIImage *listImage2 = [UIImage imageNamed:#"backicon.png.png"];
UIButton *listButton2 = [UIButton buttonWithType:UIButtonTypeCustom];
listButton2.backgroundColor=[UIColor whiteColor];
[[listButton2 layer] setBorderWidth:0.5f];
listButton2.layer.borderColor =[[UIColor blackColor] CGColor];
listButton2.layer.cornerRadius = btn.bounds.size.width / 3.4;// this value vary as per your desire
listButton2.clipsToBounds = YES;
UIFont *font = [UIFont fontWithName:#"FontAwesome" size:15.0];
UIColor *color = [UIColor blueColor];
NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName,color,NSForegroundColorAttributeName, nil];
// [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName,color,NSForegroundColorAttributeName, nil];
NSAttributedString *attributedStr = [[NSAttributedString alloc] initWithString:lab.text attributes:attrsDictionary];
// get the image size and apply it to the button frame
CGRect listButton2Frame = listButton2.frame;
listButton2Frame.size = listImage2.size;
listButton2.frame = listButton2Frame;
[listButton2 setAttributedTitle:attributedStr forState:UIControlStateNormal];
[listButton2 addTarget:self
action:#selector(LogoutClick:)
forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *jobsButton2 =
[[UIBarButtonItem alloc] initWithCustomView:listButton2];
//Notificaation Icon Button...
UILabel *lablnotification =[[UILabel alloc] init];
// lab.font = [UIFont fontWithName:#"FontAwesome" size:8];
// lab.textColor = [UIColor whiteColor];
lablnotification.text = [NSString awesomeIcon:FaHome];
UIImage *listImage4 = [UIImage imageNamed:#"notification.png"];
UIButton *listButton4 = [UIButton buttonWithType:UIButtonTypeCustom];
listButton4.backgroundColor=[UIColor whiteColor];
[[listButton4 layer] setBorderWidth:0.5f];
listButton4.layer.borderColor =[[UIColor blackColor] CGColor];
listButton4.layer.cornerRadius = btn.bounds.size.width / 3.4;// this value vary as per your desire
listButton4.clipsToBounds = YES;
UIFont *fontnotification = [UIFont fontWithName:#"FontAwesome" size:18.0];
UIColor *colornotification = [UIColor blueColor];
NSDictionary *attrsDictionarynotification = [NSDictionary dictionaryWithObjectsAndKeys:fontnotification,NSFontAttributeName,colornotification,NSForegroundColorAttributeName, nil];
// [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName,color,NSForegroundColorAttributeName, nil];
NSAttributedString *attributedStrnotification = [[NSAttributedString alloc] initWithString:lablnotification.text attributes:attrsDictionarynotification];
// get the image size and apply it to the button frame
CGRect listButton4Frame = listButton4.frame;
listButton4Frame.size = listImage4.size;
listButton4.frame = listButton4Frame;
[listButton4 setAttributedTitle:attributedStrnotification forState:UIControlStateNormal];
[listButton4 addTarget:self
action:#selector(ActualNotificationClick:)
forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *jobsButton4 =
[[UIBarButtonItem alloc] initWithCustomView:listButton4];
UIImage *listImage3 = [UIImage imageNamed:#"ec2.png"];
UIButton *listButton3 = [UIButton buttonWithType:UIButtonTypeCustom];
// get the image size and apply it to the button frame
CGRect listButton3Frame = listButton3.frame;
listButton3Frame.size = listImage3.size;
listButton3.frame = listButton3Frame;
[listButton3 setImage:listImage3 forState:UIControlStateNormal];
[listButton3 addTarget:self
action:#selector(EmployeeClick:)
forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *jobsButton3 =
[[UIBarButtonItem alloc] initWithCustomView:listButton3];
self.navigationItem.rightBarButtonItems= [NSArray arrayWithObjects:jobsButton2,jobsButton4, nil];
self.navigationItem.leftBarButtonItems=[NSArray arrayWithObjects:jobsButton3, nil];
//NSUserDefault...
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
userid = [defaults objectForKey:#"UserId"];
NSLog(#"User Id is =%#",userid);
ServerString=[defaults objectForKey:#"ServerString"];
DefaultRegionIDString=[defaults objectForKey:#"DefaultRegionIDString"];
DefaultBranchIDString=[defaults objectForKey:#"DefaultBranchIDString"];
DefaultSiteIDString=[defaults objectForKey:#"DefaultSiteIDString"];
DefaultLocationString=[defaults objectForKey:#"DefaultLocationString"];
DefaultDateString =[defaults objectForKey:#"DefaultDateString"];
DefaultTimeString =[defaults objectForKey:#"DefaultTimeString"];
DefaultEmployeeNameString=[defaults objectForKey:#"DefaultEmployeeNameString"];
DefaultRegionNameString=[defaults objectForKey:#"DefaultRegionNameString"];
DefaultBranchNameString=[defaults objectForKey:#"DefaultBranchNameString"];
DefaultSiteNameString=[defaults objectForKey:#"DefaultSiteNameString"];
DefaultEventTypeString=[defaults objectForKey:#"DefaultEventTypeString"];
DefaultIncidentTypeString=[defaults objectForKey:#"DefaultIncidentTypeString"];
DefaultsIncidentNameString=[defaults objectForKey:#"DefaultsIncidentNameString"];
SegmentStringCheck=[defaults objectForKey:#"SegmentStringCheck"];
CheckIncidentString=[defaults objectForKey:#"CheckIncidentString"];
if([DefaultEventTypeString isEqualToString:#"1"])
{
lblreportregion.text = DefaultRegionIDString;
lblreportbranch.text = DefaultBranchIDString;
lblreportsite.text = DefaultSiteIDString;
// lblreportinjurytype.text=DefaultIncidentTypeString;
txtreportlocation.text = DefaultLocationString;
txtreportdate.text = DefaultDateString;
txtreporttime.text = DefaultTimeString;
txtreportemp.text = DefaultEmployeeNameString;
txtreportregion.text=DefaultRegionNameString;
txtreportbranch.text=DefaultBranchNameString;
txtreportsite.text=DefaultSiteNameString;
// txtreportinjurytype.text = DefaultsIncidentNameString;
}
else if ([DefaultEventTypeString isEqualToString:#"2"])
{
lblnearregion.text = DefaultRegionIDString;
lblnearbranch.text = DefaultBranchIDString;
lblnearsite.text = DefaultSiteIDString;
txtnearlocation.text = DefaultLocationString;
txtneardate.text = DefaultDateString;
txtneartime.text = DefaultTimeString;
txtnearemp.text = DefaultEmployeeNameString;
txtnearregion.text=DefaultRegionNameString;
txtnearbranch.text=DefaultBranchNameString;
txtnearsite.text=DefaultSiteNameString;
}
else if ([DefaultEventTypeString isEqualToString:#"3"])
{
lblspotingregion.text = DefaultRegionIDString;
lblspotingbranch.text = DefaultBranchIDString;
lblspotingsite.text = DefaultSiteIDString;
txtspotinglocation.text = DefaultLocationString;
txtspotingdate.text = DefaultDateString;
txtspotingtime.text = DefaultTimeString;
txtsportingemp.text = DefaultEmployeeNameString;
txtspotingregion.text=DefaultRegionNameString;
txtspotingbranch.text=DefaultBranchNameString;
txtspotingsite.text=DefaultSiteNameString;
}
if([SegmentStringCheck isEqualToString:#"0"])
{
segment.selectedSegmentIndex = UISegmentedControlNoSegment;
segment.selectedSegmentIndex = 0;
viewspoting.hidden=NO;
viewnear.hidden=YES;
viewreport.hidden=YES;
}
else if ([SegmentStringCheck isEqualToString:#"1"])
{
segment.selectedSegmentIndex = UISegmentedControlNoSegment;
segment.selectedSegmentIndex = 1;
viewspoting.hidden=YES;
viewnear.hidden=NO;
viewreport.hidden=YES;
//Near...
[self nearserverconnection];
[self nearserverconnectionincident];
[self nearserverconnectionactivity];
}
else if ([SegmentStringCheck isEqualToString:#"2"])
{
segment.selectedSegmentIndex = UISegmentedControlNoSegment;
segment.selectedSegmentIndex = 2;
viewspoting.hidden=YES;
viewnear.hidden=YES;
viewreport.hidden=NO;
//Report...
[self reportserverconnection];
[self reportserverconnectioninjury];
}
else
{
segment.selectedSegmentIndex = UISegmentedControlNoSegment;
segment.selectedSegmentIndex = 0;
viewspoting.hidden=NO;
viewnear.hidden=YES;
viewreport.hidden=YES;
}
//.........................//
//Sporting Hide Code...
//Table...
tablesportingbranch.hidden=YES;
tablesportingregion.hidden=YES;
tablesportingsite.hidden=YES;
//Label...
lblsportingactivitytype.hidden=YES;
lblsportingdept.hidden=YES;
lblsportingemp.hidden=YES;
lblspotingbranch.hidden=YES;
lblspotingincidenttype.hidden=YES;
lblspotingregion.hidden=YES;
lblspotingsite.hidden=YES;
//TextFieldDelegate...
txtspotingsite.delegate=self;
txtsportingemp.delegate=self;
txtspotinglocation.delegate=self;
//Date Picker...
pickerspotingdate.hidden=YES;
pickerspotingtime.hidden=YES;
//............................//
//Near Hide Code...
//View...
// viewnear.hidden=YES;
//Table...
tablenearbranch.hidden=YES;
tablenearregion.hidden=YES;
tablenearsite.hidden=YES;
//Label...
lblnearactivitytype.hidden=YES;
lblnearbranch.hidden=YES;
lblneardept.hidden=YES;
lblnearemp.hidden=YES;
lblnearincidenttype.hidden=YES;
lblnearregion.hidden=YES;
lblnearsite.hidden=YES;
//TextFieldDelegate..
txtnearsite.delegate=self;
txtnearemp.delegate=self;
txtnearlocation.delegate=self;
//Date Picker...
pickerneardate.hidden=YES;
pickerneartime.hidden=YES;
//...........................//
//Report Hide View Code...
//View...
// viewreport.hidden=YES;
//Table...
tablereportbranch.hidden=YES;
tablereportinjurytype.hidden=YES;
tablereportregion.hidden=YES;
tablereportsite.hidden=YES;
//Label...
lblreportbranch.hidden=YES;
lblreportdept.hidden=YES;
lblreportemp.hidden=YES;
lblreportinjurytype.hidden=YES;
lblreportregion.hidden=YES;
lblreportsite.hidden=YES;
//TextFieldDelegate...
txtreportsite.delegate=self;
txtreportemp.delegate=self;
txtreportlocation.delegate=self;
//Date Picker...
pickerreporttime.hidden=YES;
pickereportdate.hidden=YES;
//.............................//
//Font Asowme
//Show...
lblspotingShow.font = [UIFont fontWithName:#"FontAwesome" size:15];
lblspotingShow.textColor = [UIColor blackColor];
lblspotingShow.text = [NSString awesomeIcon:FaEye];
//Scroll View...
[scrollspoting setContentSize:CGSizeMake(300, 500)];
[scrollnear setContentSize:CGSizeMake(300, 500)];
[scrollreport setContentSize:CGSizeMake(300, 730)];
UISwipeGestureRecognizer *gestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(swipeHandler:)];
[gestureRecognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
[self.view addGestureRecognizer:gestureRecognizer];
//Button Diamiter...
//Spoting Button...
btnsportinghideadd.layer.cornerRadius = 4; // this value vary as per your desire
btnsportinghideadd.clipsToBounds = YES;
//Near Button...
btnnearhideadd.layer.cornerRadius = 4; // this value vary as per your desire
btnnearhideadd.clipsToBounds = YES;
//Report Button...
btnreportnext.layer.cornerRadius = 4; // this value vary as per your desire
btnreportnext.clipsToBounds = YES;
//Spoting...
[self spotingserverconnection];
[self spotingserverconnectionactivity];
[self spotingserverconnectionincident];
[txtspotingsite addTarget:self action:#selector(spotingtextFieldDidChangeSite:) forControlEvents:UIControlEventEditingChanged];
// prevents the scroll view from swallowing up the touch event of child buttons
[txtnearsite addTarget:self action:#selector(neartextFieldDidChangeSite:) forControlEvents:UIControlEventEditingChanged];
[txtreportsite addTarget:self action:#selector(reporttextFieldDidChangeSite:) forControlEvents:UIControlEventEditingChanged];
UITapGestureRecognizer *tapGesturereportinjury = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(hideSubViewreportinjury)];
// prevents the scroll view from swallowing up the touch event of child buttons
tapGesturereportinjury.cancelsTouchesInView = NO;
[scrollreport addGestureRecognizer:tapGesturereportinjury];
IssueSelectedIDarray=[[NSMutableArray alloc] init];
IssueSelectedNamearray=[[NSMutableArray alloc] init];
ReportInjurySelectedNamearray=[[NSMutableArray alloc] init];
ReportInjurySelectedIDarray=[[NSMutableArray alloc] init];
[self testInternetConnection];
//Spoting Date and Time..
NSDateFormatter *Spotingdateformatter;
Spotingdateformatter = [[NSDateFormatter alloc] init];
[Spotingdateformatter setDateFormat:#"dd/MM/yyyy"];
SpotingdateString = [Spotingdateformatter stringFromDate:[NSDate date]];
NSLog(#"Current Time =%#",SpotingdateString);
CurrentDate=SpotingdateString;
NSDate * now = [NSDate date];
NSDateFormatter *Spotingtimeformatter = [[NSDateFormatter alloc] init];
[Spotingtimeformatter setDateFormat:#"hh:mm"];
SpotingTimeString = [Spotingtimeformatter stringFromDate:now];
NSLog(#"newDateString %#", SpotingTimeString);
//Near Date and Time..
NSDateFormatter *Neardateformatter;
Neardateformatter = [[NSDateFormatter alloc] init];
[Neardateformatter setDateFormat:#"dd/MM/yyyy"];
NeardateString = [Neardateformatter stringFromDate:[NSDate date]];
NSLog(#"Current Time =%#",NeardateString);
NSDate * nowNear = [NSDate date];
NSDateFormatter *Neartimeformatter = [[NSDateFormatter alloc] init];
[Neartimeformatter setDateFormat:#"hh:mm"];
NearTimeString = [Neartimeformatter stringFromDate:nowNear];
NSLog(#"newDateString %#", NearTimeString);
//Report Date and Time..
NSDateFormatter *Reportdateformatter;
Reportdateformatter = [[NSDateFormatter alloc] init];
[Reportdateformatter setDateFormat:#"dd/MM/yyyy"];
ReportdateString = [Reportdateformatter stringFromDate:[NSDate date]];
NSLog(#"Current Time =%#",ReportdateString);
NSDate * nowReport = [NSDate date];
NSDateFormatter *Reporttimeformatter = [[NSDateFormatter alloc] init];
[Reporttimeformatter setDateFormat:#"hh:mm"];
ReportTimeString = [Reporttimeformatter stringFromDate:nowReport];
NSLog(#"newDateString %#", ReportTimeString);
}
Its working to much slow. Is there is any way to speed it up?
ViewName *Incedent =[[ViewName alloc] initWithNibName:#"ViewName" bundle:nil];
[self.navigationController pushViewController:Incedent animated:YES];
I have used this code to pushviewcontroller.
You need to evaluate what your code is doing, and find out where it is slow. I don't know what this method is doing, but I'm betting the line:
[self testInternetConnection];
is one of the problems. Comment out that line, and see what happens.

Date Picker - show time between two dates (UIDatePickerModeDateAndTime)

I'm currently showing a Date Picker of the kind UIDatePickerModeCountDownTimer that uses:
- (UIDatePicker *)datePicker {
if (!_datePicker) {
_datePicker = [[UIDatePicker alloc] init];
_datePicker.datePickerMode = UIDatePickerModeCountDownTimer;
_datePicker.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.8];
}
return _datePicker;
}
- (void)setDuration:(NSTimeInterval)duration {
_duration = duration;
self.datePicker.countDownDuration = _duration;
}
... date picker, and shows (in a label) the time from current date to date chosen in future with:
- (void)update {
if (self.time) {
[self setImage:nil forState:UIControlStateNormal];
NSString *title;
NSTimeInterval timeInterval = [self.time doubleValue];
if (self.ticking) {
NSMutableString *dateFormat = [[NSMutableString alloc] init];
if (timeInterval < 0) {
[dateFormat appendString:#"-"];
}
if (fabsf(timeInterval) > 60 * 60) {
[dateFormat appendString:#"hh:"];
}
[dateFormat appendString:#"mm:ss"];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = dateFormat;
formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
title = [formatter stringFromDate:date];
if ([self.time integerValue] > 0) {
self.circleView.backgroundColor = [UIColor colorWithRed:0.373 green:0.702 blue:0.522 alpha:1];
} else {
self.circleView.backgroundColor = [UIColor colorWithRed:0.820 green:0.373 blue:0.424 alpha:1];
}
} else {
NSMutableString *text = [[NSMutableString alloc] init];
if (fabsf(timeInterval) < 60) {
// Show seconds
[text appendFormat:#"%.0fs", timeInterval];
} else if (fabsf(timeInterval) < 60 * 60) {
// Show minutes
[text appendFormat:#"%.0fm", floorf(timeInterval / 60)];
} else {
// Show hours
[text appendFormat:#"%.0fh", floorf(timeInterval / 60 / 60)];
}
title = text;
self.circleView.backgroundColor = [UIColor colorWithWhite:1.0f alpha:0.2];
}
[self setTitle:title forState:UIControlStateNormal];
return;
}
[self setTitle:nil forState:UIControlStateNormal];
[self setImage:[UIImage imageNamed:#"plus"] forState:UIControlStateNormal];
self.circleView.backgroundColor = [UIColor colorWithWhite:1.0f alpha:0.05];
}
... but I switched the DatePicker to UIDatePickerModeDateAndTime and need to figure out how to update my update method with it.
I need to show month/day in addition to hour/minute/second in the label.
If you want a method like delegate, then this can help you..
Add target to your date picker....
[myDatePicker addTarget:self action:#selector(onPickerValueChanged:) forControlEvents:UIControlEventValueChanged];
Remove target in dealloc. Otherwise if your picker is scrolling and viewController is popped, app will crash.
- (void dealloc
{
[myPicker removeTarget:self action:#selector(onPickerValueChanged:) forControlEvents:UIControlEventValueChanged];
[myPicker release];//FOR NON ARC
[super dealloc];//FOR NON ARC
}
Implement value Change like
- (IBAction)onPickerValueChanged:(id)sender
{
[self update];
}

NSMutableArray data sorting by a distance

Have a problem with my MutableArray. I've the data array in my tableview, and everything is ok, but when the data is sorting by a distance and i'm choosing an item in cell, it shows me incorrect data in new viewcontroller. It shows the data without sorting. It's like a broken link) Hope for your help)
i'm new in obj-c, so i apologise)
here is my code:
list = [[NSMutableArray alloc] init];
[list addObject:#{#"name": #"Central office", #"address":#"наб. Обводного канала, д.66А", #"phone":#"+7 (812) 320-56-21 (многоканальный)", #"workTime":#"ПН-ПТ: с 9:30 до 18:30", #"email":#"mail#ibins.ru", #"payment":#"Принимаются к оплате пластиковые карты VISA и MasterCard", #"longitude":#30.336842, #"latitude":#59.913950}];
[list addObject:#{#"name": #"Second office", #"address":#"ул. Камышовая, д.38", #"phone":#"+7 (812) 992-992-6; +7 (812) 456-26-43", #"workTime":#"Ежедневно: с 9:30 до 20:00", #"email":#"sever#ibins.ru", #"payment":#"Принимаются к оплате пластиковые карты VISA и MasterCard", #"longitude":#30.219863, #"latitude":#60.008805}];
[list addObject:#{#"name": #"Third office", #"address":#"Street name", #"phone":#"phone number", #"workTime":#"Work time", #"email":#"email address", #"longitude":#30.294254, #"latitude":#60.028728}];
[self constructList];
[self constructPins];
}
- (IBAction)switchDisplayType:(id)sender {
[UIView beginAnimations:#"View Flip" context:nil];
[UIView setAnimationDuration:0.80];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.view cache:NO];
[UIView commitAnimations];
if ([(UISegmentedControl*)sender selectedSegmentIndex] == 1) {
map.hidden = YES;
contentSV.hidden = NO;
}
else {
map.hidden = NO;
contentSV.hidden = YES;
}
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
static NSString* BridgeAnnotationIdentifier = #"bridgeAnnotationIdentifier";
MKPinAnnotationView* customPinView = [[[MKPinAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:BridgeAnnotationIdentifier] autorelease];
customPinView.pinColor = MKPinAnnotationColorRed;
customPinView.animatesDrop = YES;
customPinView.canShowCallout = YES;
UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
// NSLog(#"%#",rightButton);
[rightButton addTarget:self
action:#selector(annotationButtonTapped:)
forControlEvents:UIControlEventTouchUpInside];
customPinView.rightCalloutAccessoryView = rightButton;
return customPinView;//[kml viewForAnnotation:annotation];
}
- (void)annotationButtonTapped:(id)sender {
DetailVC *sampleVC = [[DetailVC alloc] initWithNibName:#"DetailVC" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:sampleVC animated:YES];
[sampleVC release];
for (NSDictionary *dict in list) {
if ([[dict valueForKey:#"name"] isEqualToString:selectedAnnTitle]) {
[sampleVC updateViewWithDict:dict];
}
}
}
- (void)constructPins {
for (NSDictionary *dict in list) {
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.3;
span.longitudeDelta = 0.3;
CLLocationCoordinate2D location;
location.latitude = [[dict valueForKey:#"latitude"] floatValue];
location.longitude = [[dict valueForKey:#"longitude"] floatValue];
if (location.latitude == 0.0 && location.longitude == 0.0)
return;
region.span = span;
region.center = location;
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
point.coordinate = location;
point.title = [dict valueForKey:#"name"];
[map addAnnotation:point];
[map setRegion:region animated:YES];
}
}
- (void)constructList {
int n = 0;
for (NSDictionary *dict in list) {
UIView *container = [[UIView alloc] initWithFrame:CGRectMake(0, 100*n, 320, 100)];
container.backgroundColor = [UIColor whiteColor];
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
button.tag = n;
[button addTarget:self action:#selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
[container addSubview:button];
NSString *str = [NSString stringWithFormat:#"%#\nAddress: %#\nPhone: %#\nWork Time: %#", [dict valueForKey:#"name"], [dict valueForKey:#"address"], [dict valueForKey:#"phone"], [dict valueForKey:#"workTime"]];
UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 300, 80)];
nameLabel.textAlignment = NSTextAlignmentLeft;
nameLabel.numberOfLines = 0;
nameLabel.text = str;
nameLabel.font = [UIFont fontWithName:#"HelveticaNeue" size:12.0];
[container addSubview:nameLabel];
UIView *separator = [[UIView alloc]initWithFrame:CGRectMake(0, 99, 320, 1)];
separator.backgroundColor = [UIColor darkGrayColor];
[container addSubview:separator];
[contentSV addSubview:container];
n++;
contentSV.contentSize = CGSizeMake(0, 100*n);
}
}
- (float)distanceBetweenLat1:(float)tlat1 lon1:(float)tlon1 lat2:(float)tlat2 lon2:(float)tlon2 {
float result = 0.0;
int R = 6371;
float currentLatitude = tlat1;
float currentLongtitude = tlon1;
float lat2 = tlat2;
float lon2 = tlon2;
float dLat = (lat2-currentLatitude)*M_PI/180;
float dLon = (lon2-currentLongtitude)*M_PI/180;
float nlLat = currentLatitude*M_PI/180;
lat2 = lat2*M_PI/180;
float a = sin(dLat/2) * sin(dLat/2) + sin(dLon/2) * sin(dLon/2) * cos(nlLat) * cos(lat2);
float c = 2 * atan2(sqrt(a), sqrt(1-a));
result = R * c;
return result;
}
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
selectedAnnTitle = [view.annotation title];
return;
DetailVC *sampleVC = [[DetailVC alloc] initWithNibName:#"DetailVC" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:sampleVC animated:YES];
NSString *ttl = [view.annotation title];
for (NSDictionary *dict in list) {
if ([[dict valueForKey:#"name"] isEqualToString:ttl]) {
[sampleVC updateViewWithDict:dict];
}
}
[map deselectAnnotation:view.annotation animated:NO];
}
- (void)buttonTapped:(id)sender {
DetailVC *sampleVC = [[DetailVC alloc] initWithNibName:#"DetailVC" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:sampleVC animated:YES];
int n = 0;
for (NSDictionary *dict in list) {
if (n == [sender tag]) {
[sampleVC updateViewWithDict:dict];
}
n++;
}
}
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
NSLog(#"didUpdateUserLocation");
MKAnnotationView* annotationView = [mapView viewForAnnotation:userLocation];
annotationView.canShowCallout = NO;
if (!userLocationUpdated) {
if (userLocation.coordinate.latitude > 0.1 && userLocation.coordinate.longitude > 0.1) {
// NSLog(#"SORT BY DISTANCE");
userLocationUpdated = YES;
for (int i = 0; i < [list count]; i++) {
NSMutableDictionary *record = [[NSMutableDictionary alloc] initWithDictionary:[list objectAtIndex:i]];
float latitude = [[record valueForKey:#"latitude"] floatValue];
float longitude = [[record valueForKey:#"longitude"] floatValue];
float dist = [self distanceBetweenLat1:map.userLocation.coordinate.latitude lon1:map.userLocation.coordinate.longitude lat2:latitude lon2:longitude];
NSNumber *distN = [NSNumber numberWithFloat:dist];
[record setObject:distN forKey:#"distance"];
[list replaceObjectAtIndex:i withObject:record];
}
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:#"distance" ascending:YES];
NSArray *itemsListSorted = [[NSArray alloc] initWithArray:list];
itemsListSorted = [itemsListSorted sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
for (UIView *view in contentSV.subviews) {
[view removeFromSuperview];
}
for (int i = 0; i < [itemsListSorted count]; i++) {
UIView *container = [[UIView alloc] initWithFrame:CGRectMake(0, 100*i, 320, 100)];
container.backgroundColor = [UIColor whiteColor];
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
button.tag = i;
[button addTarget:self action:#selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
[container addSubview:button];
NSString *str = [NSString stringWithFormat:#"%#\nAddress: %#\nPhone: %#\nWorkTime: %#", [[itemsListSorted objectAtIndex:i] valueForKey:#"name"], [[itemsListSorted objectAtIndex:i] valueForKey:#"address"], [[itemsListSorted objectAtIndex:i] valueForKey:#"phone"], [[itemsListSorted objectAtIndex:i] valueForKey:#"workTime"]];
UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 300, 80)];
nameLabel.textAlignment = NSTextAlignmentLeft;
nameLabel.numberOfLines = 0;
nameLabel.text = str;
nameLabel.font = [UIFont fontWithName:#"HelveticaNeue" size:12.0];
[container addSubview:nameLabel];
UILabel *distanceLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 2, 300, 21)];
distanceLabel.textAlignment = NSTextAlignmentRight;
distanceLabel.text = [NSString stringWithFormat:#"%.1f км", [[[itemsListSorted objectAtIndex:i] valueForKey:#"distance"] floatValue]];
distanceLabel.font = [UIFont fontWithName:#"HelveticaNeue" size:12.0];
distanceLabel.textColor = [UIColor lightGrayColor];
[container addSubview:distanceLabel];
UIView *separator = [[UIView alloc]initWithFrame:CGRectMake(0, 99, 320, 1)];
separator.backgroundColor = [UIColor darkGrayColor];
[container addSubview:separator];
[contentSV addSubview:container];
contentSV.contentSize = CGSizeMake(0, 100*(i+1));
}
}
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#end
Although there are numerous issues with this code (the least of which are some minor precision issues with the distance calculation), the problem is not with the distance calculation.
The detail view controller shows incorrect data because it is given the data from the list array which is not itself sorted by distance.
In the didUpdateUserLocation delegate method, the contents of list are copied to a local array named itemsListSorted.
Only the itemsListSorted array is sorted by distance and then the display is updated using this local array.
But the original list array (which the buttonTapped method uses as the source of the data to send to the detail view controller) is never updated.
So if "Central Office" is at index 0 in list but gets moved to index 2 in itemsListSorted, the display shows the correct position but when you tap on it, the buttonTapped method sends the item at index 2 from the list array which does not have "Central Office" (it's still at index 0 in list).
One way to fix this problem is to stop using a local array and sort the list array directly.
In didUpdateUserLocation, you could replace these two lines:
NSArray *itemsListSorted = [[NSArray alloc] initWithArray:list];
itemsListSorted = [itemsListSorted sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
with this:
[list sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
and then replace all references to itemsListSorted in the same method with list.
Regarding the other issues with the code, there is not enough room to point them all out or explain them in one answer. However, here are just a few highlights:
Instead of a manually creating a "table view", use an actual UITableView.
Instead of manually calculating distance between coordinates, use the distanceFromLocation method in the CLLocation class or the MKMetersBetweenMapPoints function.
In viewForAnnotation, you should return nil if annotation is of type MKUserLocation otherwise it will appear as a red pin just like the others.
Use ARC instead of manual memory management.

iOS calendar integration to app

I having an app so i just added some event or remainder (football match,movie) in my app for some particular date and time.
And this add event i also want to display in iphone calendar.
thanks and regards.
Have you checked out EventKit?
You can use simple JTCalender for this
first oyu have to include JT Calender framework for the project
You have to create two views in your UIViewController:
The first view is JTCalendarMenuView and it represents the part with the months names. This view is optional.
The second view is JTHorizontalCalendarView or JTVerticalCalendarView, it represents the calendar itself.
Your UIViewController have to implement JTCalendarDelegate, all methods are optional.
in .h file
#import <UIKit/UIKit.h>
#import "CustomTableViewCell.h"
#import "JTCalendar/JTCalendar.h"
#interface CalendarViewController : UIViewController<UITableViewDataSource,UITableViewDelegate,JTCalendarDelegate>
#property (strong, nonatomic) JTCalendarMenuView *calendarMenuView;
#property (strong, nonatomic) JTHorizontalCalendarView *calendarContentView;
#property (strong, nonatomic) JTCalendarManager *calendarManager;
#property (weak, nonatomic) IBOutlet NSLayoutConstraint *calendarContentViewHeight;
#end
.m file
------------
#import "CalendarViewController.h"
#import "ApptWindowView.h"
#import "SVProgressHUD.h"
#interface CalendarViewController () < UITextFieldDelegate>{
NSMutableDictionary *dayDateDict;
NSMutableArray*jsonDate,*dateAr1,*dateAr2;
UITableView *appointTableView;
CGSize screenRect;
NSString *dateAfterString;
int fontSize,headerBtnfont,height;
NSDateFormatter *dateFormat1 ;
NSString*cmpDay;
int count;
NSString * clickedDate;
NSString *day ;
NSMutableDictionary *_eventsByDate;
NSDate *_todayDate;
NSDate *_minDate;
NSDate *_maxDate;
NSDate *_dateSelected;
UIActivityIndicatorView *activityIndicator;
int i;
}
#end
#implementation CalendarViewController
- (void)viewDidLoad
{
[super viewDidLoad];
i=0;
dayDateDict=[[NSMutableDictionary alloc]init];
dateAr1=[[NSMutableArray alloc]init];
dateAr2=[[NSMutableArray alloc]init];
screenRect=[[UIScreen mainScreen]bounds].size;
//Create header here
self.view.backgroundColor=[UIColor colorWithRed:(CGFloat)233/255 green:(CGFloat)239/255 blue:(CGFloat)239/255 alpha:1];
UIView * headerView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 55)];
headerView.backgroundColor =[UIColor whiteColor];
[self.view addSubview:headerView];
UILabel * titleLable =[[UILabel alloc]initWithFrame:CGRectMake(60, 25, [UIScreen mainScreen].bounds.size.width-120, 25)];
titleLable.text =#"CHOOSE APPOINTMENT";
titleLable.textAlignment = NSTextAlignmentCenter;
titleLable.font =[UIFont systemFontOfSize:12];
[headerView addSubview:titleLable];
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
[backButton setImage:[UIImage imageNamed:#"back_btn.png"] forState:UIControlStateNormal];
[backButton setFrame:CGRectMake(15, 30, 45, 15)];
[backButton addTarget:self action:#selector(backAction) forControlEvents:UIControlEventTouchUpInside];
[headerView addSubview:backButton];
UIButton *nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
[nextButton setImage:[UIImage imageNamed:#"next_btn.png"] forState:UIControlStateNormal];
[nextButton setFrame:CGRectMake([UIScreen mainScreen].bounds.size.width-60, 30, 45, 15)];
[nextButton addTarget:self action:#selector(continueAction) forControlEvents:UIControlEventTouchUpInside];
[headerView addSubview:nextButton];
[self activityAction];
dispatch_async(dispatch_get_global_queue(0, 0),^{
dispatch_async(dispatch_get_main_queue(),^{
// [self createUI];
[self fetchSchedule];
_calendarManager = [JTCalendarManager new];
_calendarManager.delegate = self;
[self createMinAndMaxDate];
_calendarContentView=[JTHorizontalCalendarView new];
_calendarContentView.frame = CGRectMake(20, 100,[UIScreen mainScreen].bounds.size.width-40 , [UIScreen mainScreen].bounds.size.width-40);
_calendarContentView.backgroundColor=[UIColor whiteColor];
[_calendarManager setContentView:_calendarContentView];
[self.view addSubview:_calendarContentView];
_calendarMenuView=[JTCalendarMenuView new];
_calendarMenuView.frame=CGRectMake(20, 55,[UIScreen mainScreen].bounds.size.width-40 ,50);
_calendarMenuView.backgroundColor=[UIColor clearColor];
[self.view addSubview:_calendarMenuView];
[_calendarManager setMenuView:_calendarMenuView];
[_calendarManager setDate:[NSDate date]];
[activityIndicator stopAnimating];
});
});
[self createUI];
}
-(void)continueAction{
ApptWindowView *apptWindow=[[ApptWindowView alloc]init];
[self.navigationController pushViewController:apptWindow animated:YES];
}
- (UIView<JTCalendarDay> *)calendarBuildDayView:(JTCalendarManager *)calendar
{
JTCalendarDayView *view = [JTCalendarDayView new];
view.textLabel.font = [UIFont fontWithName:#"Avenir-Light" size:13];
view.textLabel.textColor = [UIColor blackColor];
return view;
}
NSError *error; NSURLResponse * urlResponse;
NSURL * url =[NSURL URLWithString:fetchScheduleService];
NSMutableURLRequest * request =[[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:50];
NSString * body =[NSString stringWithFormat:#"departmentId=%d",[SingletonClass sharedSingleton].deptId ];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSData * data =[NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
if (!data) {
[SVProgressHUD dismiss];
return;
}
id jsonResponse =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(#"schedule jason---->%#",jsonResponse);
if ([[jsonResponse objectForKey:#"code"] isEqualToNumber:[NSNumber numberWithInt:200]]) {
jsonDate=[jsonResponse objectForKey:#"data"];
[self convertTimeStamp];
}
//dispatch_async(dispatch_get_main_queue(),^{
// [SVProgressHUD dismiss];
//[self createUI];
// });
// });
}
#pragma mark-Create UI/Table View
-(void)createUI{
appointTableView = [[UITableView alloc]init];
appointTableView.frame = CGRectMake(10, 100+screenRect.width-40+10, screenRect.width-20, screenRect.height-( 100+screenRect.width-40+10));
appointTableView.delegate = self;
appointTableView.dataSource = self;
appointTableView.backgroundColor =[UIColor clearColor];
appointTableView.showsVerticalScrollIndicator = NO;
appointTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
[self.view addSubview:appointTableView];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [[dayDateDict objectForKey:clickedDate] count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
CustomTableViewCell * cell =(CustomTableViewCell*) [tableView cellForRowAtIndexPath:indexPath];
if (!cell) {
cell = [[CustomTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"calender"];
cell.backgroundColor = [UIColor clearColor];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
[dateFormat1 setDateFormat:#"HH:mm"];
NSDate * aptTime =[dateFormat1 dateFromString:[[dayDateDict objectForKey:clickedDate]objectAtIndex:indexPath.row] ];
NSDate *dateAfter=[aptTime dateByAddingTimeInterval:(1800) ];
dateAfterString =[dateFormat1 stringFromDate:dateAfter];
NSString *dis=[NSString stringWithFormat:#"%#-%#",[[dayDateDict objectForKey:clickedDate]objectAtIndex:indexPath.row],dateAfterString];
cell.appointmentTime.text =dis;
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
return 100;
}
return 60;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
ApptWindowView *apptWindow=[[ApptWindowView alloc]init];
[self.navigationController pushViewController:apptWindow animated:YES];
NSLog(#"clicked date-->%#",[[dayDateDict objectForKey:clickedDate]objectAtIndex:indexPath.row]);
NSDate * aptTime =[dateFormat1 dateFromString:[[dayDateDict objectForKey:clickedDate]objectAtIndex:indexPath.row] ];
NSDate *dateAfter=[aptTime dateByAddingTimeInterval:(1800) ];
dateAfterString =[dateFormat1 stringFromDate:dateAfter];
NSString *dis=[NSString stringWithFormat:#"%# to %# on %#",[[dayDateDict objectForKey:clickedDate]objectAtIndex:indexPath.row],dateAfterString,day];
[[NSUserDefaults standardUserDefaults]setObject:dis forKey:#"appointmentTime"];
[[NSUserDefaults standardUserDefaults]synchronize];
}
#pragma mark-convert timeStamp to date
-(void)convertTimeStamp{
for( NSString*valueForDate in jsonDate){
NSTimeInterval timeSec=[valueForDate doubleValue];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeSec];
NSLog(#"\ndate are-->%#",date);
[self separateDate:date];
}
}
#pragma mark-separate date and Time
-(void)separateDate:(NSDate*)date1{
dateFormat1 = [[NSDateFormatter alloc] init];
[dateFormat1 setDateFormat:#"HH:mm"];
NSString * resultTime =[dateFormat1 stringFromDate:date1];
NSLog(#"date is-->%#",resultTime);
[dateFormat1 setDateFormat:#"dd-MM-YYYY"];
NSString *resultDay=[dateFormat1 stringFromDate:date1];
NSLog(#"day is-->%#",resultDay);
if([cmpDay isEqual:resultDay] || cmpDay==nil){
if(count!=1){
[dateAr1 addObject:resultTime];
}
if(count==1){
[dateAr2 addObject:resultTime];
}
}
else{
count=1;
dateAr2=[[NSMutableArray alloc]init];
[dateAr2 addObject:resultTime];
}
cmpDay=resultDay;
if(count!=1){
[dayDateDict setObject:dateAr1 forKey:resultDay];
}
else{
[dayDateDict setObject:dateAr2 forKey:resultDay];
}
NSLog(#"dictionary--->%#",dayDateDict);
}
#pragma mark - Buttons callback
- (IBAction)didGoTodayTouch
{
[_calendarManager setDate:_todayDate];
}
- (IBAction)didChangeModeTouch
{
_calendarManager.settings.weekModeEnabled = !_calendarManager.settings.weekModeEnabled;
[_calendarManager reload];
CGFloat newHeight = 300;
if(_calendarManager.settings.weekModeEnabled){
newHeight = 85.;
}
self.calendarContentViewHeight.constant = newHeight;
[self.view layoutIfNeeded];
}
#pragma mark - CalendarManager delegate
// Exemple of implementation of prepareDayView method
// Used to customize the appearance of dayView
- (void)calendar:(JTCalendarManager *)calendar prepareDayView:(JTCalendarDayView *)dayView
{
// Today
if([_calendarManager.dateHelper date:[NSDate date] isTheSameDayThan:dayView.date]){
dayView.circleView.hidden = NO;
dayView.circleView.backgroundColor = [UIColor blueColor];
dayView.dotView.backgroundColor = [UIColor whiteColor];
dayView.textLabel.textColor = [UIColor whiteColor];
}
// Selected date
else if(_dateSelected && [_calendarManager.dateHelper date:_dateSelected isTheSameDayThan:dayView.date]){
dayView.circleView.hidden = NO;
dayView.circleView.backgroundColor = [UIColor redColor];
dayView.dotView.backgroundColor = [UIColor whiteColor];
dayView.textLabel.textColor = [UIColor whiteColor];
}
// Other month
else if(![_calendarManager.dateHelper date:_calendarContentView.date isTheSameMonthThan:dayView.date]){
dayView.circleView.hidden = YES;
dayView.dotView.backgroundColor = [UIColor redColor];
dayView.textLabel.textColor = [UIColor lightGrayColor];
}
// Another day of the current month
else{
dayView.circleView.hidden = YES;
dayView.dotView.backgroundColor = [UIColor redColor];
dayView.textLabel.textColor = [UIColor blackColor];
}
if([self haveEventForDay:dayView.date]){
dayView.dotView.hidden = NO;
}
else{
dayView.dotView.hidden = YES;
}
}
- (void)calendar:(JTCalendarManager *)calendar didTouchDayView:(JTCalendarDayView *)dayView
{
_dateSelected = dayView.date ;
NSLog(#"orginal Clicked day-->%#",dayView.date);
NSDateFormatter *dateFormat2 = [[NSDateFormatter alloc] init];
[dateFormat2 setDateFormat:#"dd-MM-YYYY"];
clickedDate =[dateFormat2 stringFromDate:_dateSelected];
NSLog(#"Selected date===>%#",clickedDate);
NSString* s= [dayDateDict objectForKey:clickedDate];
NSLog(#"time is===>%#",s);
[dateFormat2 setDateFormat:#"EEE, MMM dd "];
day =[dateFormat2 stringFromDate:_dateSelected];
NSLog(#"Selected day===>%#",day);
// Animation for the circleView
dayView.circleView.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.1, 0.1);
[UIView transitionWithView:dayView
duration:.3
options:0
animations:^{
dayView.circleView.transform = CGAffineTransformIdentity;
[_calendarManager reload];
} completion:nil];
// Load the previous or next page if touch a day from another month
if(![_calendarManager.dateHelper date:_calendarContentView.date isTheSameMonthThan:dayView.date]){
if([_calendarContentView.date compare:dayView.date] == NSOrderedAscending){
[_calendarContentView loadNextPageWithAnimation];
}
else{
[_calendarContentView loadPreviousPageWithAnimation];
}
}
[appointTableView reloadData];
}
#pragma mark - CalendarManager delegate - Page mangement
// Used to limit the date for the calendar, optional
- (BOOL)calendar:(JTCalendarManager *)calendar canDisplayPageWithDate:(NSDate *)date
{
return [_calendarManager.dateHelper date:date isEqualOrAfter:_minDate andEqualOrBefore:_maxDate];
}
- (void)calendarDidLoadNextPage:(JTCalendarManager *)calendar
{
// NSLog(#"Next page loaded");
}
- (void)calendarDidLoadPreviousPage:(JTCalendarManager *)calendar
{
// NSLog(#"Previous page loaded");
}
#pragma mark - Fake data
- (void)createMinAndMaxDate
{
_todayDate = [NSDate date];
// Min date will be 2 month before today
_minDate = [_calendarManager.dateHelper addToDate:_todayDate months:-3];
// Max date will be 2 month after today
_maxDate = [_calendarManager.dateHelper addToDate:_todayDate months:3];
}
- (BOOL)haveEventForDay:(NSDate *)date
{
if(i>=[dayDateDict allKeys].count){
i=0;
}
NSDateFormatter *dateFormatter;
dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"dd-MM-YYYY"];
NSString *key = [dateFormatter stringFromDate:date];
while(i<[dayDateDict allKeys].count){
if([key isEqual:[[dayDateDict allKeys]objectAtIndex:i]]){
i++;
return YES;
}
else
return NO;
}
return NO;
}
#pragma mark-Activity Indicator
-(void)activityAction{
CGSize windowSize =[UIScreen mainScreen].bounds.size;
activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
activityIndicator.frame = CGRectMake(windowSize.width/2-20, windowSize.height/2-55,40 ,40);
activityIndicator.color = [UIColor blackColor];
activityIndicator.alpha = 1;
[self.view addSubview:activityIndicator];
//[self placeSearchbaseId];
[activityIndicator startAnimating];
}
#end
I am fetching json data feching time form json as time stamp format and converting to local time
Then i am creating an events for it in the calender
You have third party apps like Kal which supports calendar integration. Check this link:
Kal Calendar
Hope it helps

Resources