iOS. Table View Cell swipe hard working - ios

I have custom table view cell. And this code for swipe-deletion:
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
return reportingCellIndexPath != indexPath;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
NSInteger result = [self.messagesModel numberOfDifferentDayDatesInMessages];
return result;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSDate *sectionDate = [self.messagesModel dayDateAtNumber:section];
NSInteger rowsCount = [self.messagesModel numberOfMessagesWithDayDate:sectionDate];
return rowsCount;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSInteger realMessageIndex = [self.messagesModel fullMessageIndexForMessageWithDayDateNumber:indexPath.section index:indexPath.row];
SDMessage *message = [self.messagesModel messageAtIndex:realMessageIndex];
// SDMessage *message = [self.messagesModel messageAtIndex:indexPath.row withDayDateAtNumber:indexPath.section];
static NSString *messageCellId = #"messageCellId";
SDMessageCell *_messageCell = [tableView dequeueReusableCellWithIdentifier:messageCellId];
if (_messageCell == nil) {
_messageCell = [[SDMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:messageCellId];
}
[_messageCell rebuildWithMessage:message];
_messageCell.delegate = self;
if ([reportingCellIndexPath isEqual:indexPath] &&
![_messageCell reportViewIsShowing]) {
[_messageCell showReportViewWithMessagesModel:self.messagesModel messageIndex:realMessageIndex];
} else if ([_messageCell reportViewIsShowing]) {
[_messageCell hideReportView];
}
return _messageCell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
CGFloat result = [self tableView:tableView cellForRowAtIndexPath:indexPath].frame.size.height;
return result;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 40;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSDate *sectionDate = [self.messagesModel dayDateAtNumber:section];
if (sectionDate != nil) {
return [self sectionTitleForSectionDate:sectionDate];
} else {
return #"";
}
}
- (NSString *)sectionTitleForSectionDate:(NSDate *)date {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];
NSDateComponents *dateComponents = [calendar components:
NSYearCalendarUnit |
NSMonthCalendarUnit |
NSDayCalendarUnit |
NSWeekdayCalendarUnit |
NSWeekCalendarUnit
fromDate:date];
NSDateComponents *nowComponents = [calendar components:NSYearCalendarUnit |
NSMonthCalendarUnit |
NSDayCalendarUnit |
NSWeekdayCalendarUnit |
NSWeekCalendarUnit
fromDate:now];
if (dateComponents.year == nowComponents.year &&
dateComponents.month == nowComponents.month &&
dateComponents.week == nowComponents.week) {
if (nowComponents.weekday - dateComponents.weekday < 2) {
[dateFormatter setDoesRelativeDateFormatting:YES];
} else {
[dateFormatter setDateFormat:#"EEEE"];
}
}
return [dateFormatter stringFromDate:date];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self cancelSearchField];
NSInteger realMessageIndex = [self.messagesModel fullMessageIndexForMessageWithDayDateNumber:indexPath.section index:indexPath.row];
if (indexPath.row < self.messagesModel.size && realMessageIndex > -1) {
[self.messagesModel selectMessageAtIndex:realMessageIndex];
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
self.refreshBeforeShowing = NO;
[self.navigationController pushViewController:self.detailViewController animated:YES];
}
}
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
NSInteger realMessageIndex = [self.messagesModel fullMessageIndexForMessageWithDayDateNumber:indexPath.section index:indexPath.row];
[SDModalLoadingIndicator showLoading];
[self.messagesModel deleteMessageAtIndex:realMessageIndex success:^() {
[SDModalLoadingIndicator hideLoading];
NSString *msg = NSLocalizedString(#"Message has been deleted", nil);
[[[[iToast makeText:msg]
setDuration:iToastDurationNormal]
setGravity:iToastGravityBottom] show];
[self.tableView reloadData];
} failureCallback:^(NSString *message, NSMutableArray *validationErrors, NSError *error) {
[SDModalLoadingIndicator hideLoading];
[SDFailureHandler handleConnectFailure:message withError:error];
}];
}
}
But almost always it don't show delete button on swipe.(Sometimes button will be showing). Do somebody know why?
I've tried to debug this thing check all views by debugger, and they have only system gesture recognizers(pan, tap, long press, edge).
Also I can say that this method "tableView:canEditRowAtIndexPath:" is called each time I swipe cell but nothing happened.(In most cases)

You need to make sure you also have a commitEditingStyle delegate function setup.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle != UITableViewCellEditingStyleDelete)
return;
// perform the delete!
}
Also, remember the swipe to delete is only present when the tableView isn't being edited (in edit mode, the minus button is visible on the rows instead).

I, just forgot that my application was using side menu. So side menu was adding pan gesture on my view for closing and opening on drag event.
And I understand if you have all necessary methods implemented and delete on swipe don't work. ALWAYS try to find some gesture or element that is catching you touch event.

Related

Calendar Dates in TableView with Infinite Scrolling

I am trying to implement to show the calendar dates in TableViewCell. I am able to achieved the filled with current year. But As soon I hit the bottom of the table I need to populate next year and if I hit at top of TableView then previous year should be populated.
Pasting code which I have implemented.
- (void)fillDatesWithCalendarUnit:(NSCalendarUnit)unit withDate:(NSDate*)date
{
NSDate *today = date;
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDate *beginning;
NSTimeInterval length;
[calendar rangeOfUnit:unit startDate:&beginning interval:&length forDate:today];
NSDate *end = [beginning dateByAddingTimeInterval:length-1];
[self fillDatesFromDate:beginning toDate:end];
}
- (void)fillDatesFromDate:(NSDate *)fromDate toDate:(NSDate *)toDate
{
NSAssert([fromDate compare:toDate] == NSOrderedAscending, #"toDate must be after fromDate");
NSDateComponents *days = [[NSDateComponents alloc] init];
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSInteger dayCount = 0;
while(YES){
[days setDay:dayCount++];
NSDate *date = [calendar dateByAddingComponents:days toDate:fromDate options:0];
if([date compare:toDate] == NSOrderedDescending) break;
[_dates addObject:date];
}
[self.tableView reloadData]; //_dates mutableArray
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.dates.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
AgendaCustomCell *cell = [self.tableView dequeueReusableCellWithIdentifier:#"Cell"];
cell.date.text = [NSString stringWithFormat:#"%#",_dates[indexPath.row]];
if (indexPath.row == _dates.count-1) {
NSLog(#"load more");
NSDate *tomorrow = [NSDate dateWithTimeInterval:(48*60*60) sinceDate:_dates[indexPath.row]];
NSLog(#"last daye - %# ,tomorrow - %#",_dates[indexPath.row],tomorrow);
[self fillDatesWithCalendarUnit:NSCalendarUnitYear withDate:_dates[indexPath.row]];
}
return cell;
}
I have implemented the logic for show infinite future dates on scrolling.
- (void)viewDidLoad {
[super viewDidLoad];
_dates = [NSMutableArray new];
[self fillCurrentYear];
}
- (void)fillCurrentYear
{
[self fillDatesWithCalendarUnit:NSCalendarUnitYear withDate:[NSDate new
] isLoadMore:NO];
}
pragma mark Private methods
- (void)fillDatesWithCalendarUnit:(NSCalendarUnit)unit withDate:(NSDate*)date isLoadMore:(BOOL)isBool
{
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDate *beginning;
NSTimeInterval length;
if (isBool) {
beginning = _dates[[_dates count]-1];
}
[calendar rangeOfUnit:unit startDate:&beginning interval:&length forDate:date];
NSDate *end = [beginning dateByAddingTimeInterval:length-1];
[self fillDatesFromDate:beginning toDate:end];
}
- (void)fillDatesFromDate:(NSDate *)fromDate toDate:(NSDate *)toDate
{
NSAssert([fromDate compare:toDate] == NSOrderedAscending, #"toDate must be after fromDate");
// NSMutableArray *dates = [[NSMutableArray alloc] init];
NSDateComponents *days = [[NSDateComponents alloc] init];
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSInteger dayCount = 0;
while(YES){
[days setDay:dayCount++];
NSDate *date = [calendar dateByAddingComponents:days toDate:fromDate options:0];
if([date compare:toDate] == NSOrderedDescending) break;
[_dates addObject:date];
}
// _dates = dates;
[self.tableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
AgendaCell *cell = [self.tableView dequeueReusableCellWithIdentifier:#"Cell"];
cell.date.text = [NSString stringWithFormat:#"%#",_dates[indexPath.row]];
if (indexPath.row == _dates.count-1) {
NSLog(#"load more");
NSDate *tomorrow = [NSDate dateWithTimeInterval:(48*60*60) sinceDate:_dates[indexPath.row]];
NSLog(#"last daye - %# ,tomorrow - %#",_dates[indexPath.row],tomorrow);
[self fillDatesWithCalendarUnit:NSCalendarUnitYear withDate:tomorrow isLoadMore:YES];
}
return cell;
}

How to move cell more to left when swipe cell to delete

I'm new in iOS development.
I found an issue when I added code to support swipe to delete in cell, like the picture below.
How can I move cell more left when I swipe?
My code:
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView setEditing:YES animated:YES];
return UITableViewCellEditingStyleDelete;
}
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
return #"删除";
}
Thanks!
#Retro I added cellForRowAtIndexPath method below
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *reuseIdentifier = #"cell";
MainTableViewCell *cell = (MainTableViewCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier forIndexPath:indexPath];
NSDictionary *data = [dateArray objectAtIndex:indexPath.row];
cell.titleLabel.text = [data objectForKey:#"Title"];
cell.dateLabel.text = [data objectForKey:#"Date"];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd"];
NSDate *past = [formatter dateFromString:[data objectForKey:#"Date"]];
NSTimeInterval distance = [past timeIntervalSinceNow];
NSInteger iDat = distance / ( 86400 ) ;
NSString *distanceString = [NSString stringWithFormat:#"%d", (iDat < 0 ? -1 * iDat : iDat)];
if (iDat < 0) {
cell.daysLabel.textColor = [UIColor blueColor];
} else {
}
cell.daysLabel.text = distanceString;
cell.index = indexPath.row;
return cell;
}

Inline date picker crashed on second attempt

I have been struggling for this issue for two week now. but by the help of StackOverflow people I have came up with 95% successful implementation..
Here is my problem.. and now I could load my results with the picker cell [First most cell] when the date is selected.
Now I have another issue...when i run my application at first time, it is works as I expected..but when i tap the first most cell to pick a different date , then the application crashed..
Here is the log output...
below is my codes for the implementation
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSDictionary* reqFdate= [ScheduleView getRequestForDate];
if (reqFdate.count == 0) {
NSInteger numberOfRows = [self.persons count];
if ([self datePickerIsShown]){
numberOfRows++;
}
return numberOfRows;
}
else{
return reqFdate.count + 1;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell;
NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// display in 12HR/24HR (i.e. 11:25PM or 23:25) format according to User Settings
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString *currentTime = [dateFormatter stringFromDate:today];
NSDate *date=[dateFormatter dateFromString:currentTime];
if(indexPath.row==0){
VCPerson *person = self.persons[0];
cell = [self createPersonCell:person];
}
else if ([self datePickerIsShown] && (self.datePickerIndexPath.row == 1)){
// VCPerson *person = self.persons[indexPath.row -1];
cell = [self createPickerCell:date];
}
else{
cellForDatePickCell *cell = (cellForDatePickCell*)[self.tableView dequeueReusableCellWithIdentifier:kOtherCellIdentifier];
cell.delegate_Dtepick = self;
return cell;
}
if(indexPath.section!=0 && tapfirstCell) {
UITableViewCell *cell = (UITableViewCell*)[self.tableView dequeueReusableCellWithIdentifier:kOtherCellIdentifier forIndexPath:indexPath];
//cell.delegate_Dtepick = self;
NSDictionary *dictionary = [_dataArray objectAtIndex:indexPath.section];
NSArray *array = [dictionary objectForKey:#"data"];
NSString *cellValue = [array objectAtIndex:indexPath.row];
cell.textLabel.text =cellValue;
}
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self.tableView beginUpdates];
if ([self datePickerIsShown] && (self.datePickerIndexPath.row - 1 == indexPath.row)){
[self hideExistingPicker];
// [self.tableView reloadData];
//[self viewDidLoad];
//call the service and take the results
NSString* selecteDate = [ScheduleView getDate];
NSString* prsonID =[LoginView getPersonID];
NSDictionary* parms = [NSDictionary dictionaryWithObjectsAndKeys:prsonID,#"caregiverPersonId",selecteDate,#"selectedDate", nil];
jsonpaser* jp = [[jsonpaser alloc]init];
[jp getWebServiceResponce:#"http://qa.vardle.com/Mobile/WebServices/AppointmentService.asmx/GetAppointments" :parms success:^(NSDictionary *responseObject)
{
requestsF_date = responseObject;
NSLog(#"RESPONSEFORDATE_IN DIDSELECT :%#",requestsF_date);
NSArray* indexpaths = [self getIndexPaths];
NSLog(#"indexPATHS %#",indexpaths);
[self.tableView reloadData];
}];
// cellForDatePickCell *cell = (cellForDatePickCell*)[self.tableView dequeueReusableCellWithIdentifier:kOtherCellIdentifier forIndexPath:indexPath];
// cell.delegate_Dtepick = self;
//tapfirstCell = true;
/*
cellForDatePickCell *cell=(cellForDatePickCell*)[tableView cellForRowAtIndexPath:indexPath];
if(![cell.textLabel.text isEqualToString:#"5/23/14"])
{
return;
}
*/
if (tapfirstCell==false) {
tapfirstCell = true;
}
else{
tapfirstCell = false;
}
}else {
NSIndexPath *newPickerIndexPath = [self calculateIndexPathForNewPicker:indexPath];
if ([self datePickerIsShown]){
[self hideExistingPicker];
}
[self showNewPickerAtIndex:newPickerIndexPath];
self.datePickerIndexPath = [NSIndexPath indexPathForRow:newPickerIndexPath.row + 1 inSection:0];
}
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
[self.tableView endUpdates];
}
please someone tell me where is the issue..why app is crashed when i try to pick a date second time..
please help
i have fix my issue... i didnt deleted the rows before i start to show the date picker again..
here is the full code
here what i did was : i use Inline Datepicker with the table view [date picker will show by selecting the first cell of the table view].according to the date selected from the picker, i am displaying my custom cells below the first cell.[because the first cell always there to pick a date from a date picker].
if someone want to do the same thing which i did i think my code will help you
thank you

Have JSON data, would like to show with sections in IOS6 app

I have retrieved my events from a shared google calendar i IOS, and are displaying them in a tableview. As for right now, they're simplty shown with the event title as the title, and the eventtime as the subtitle. I'd like to use the date (eventtime) as a section header in stead, so that all events on for instance march 31st where shown in a group, with the time as a "right detail"
My code looks like this:
#interface MasterViewController () {
NSArray *events;
}
#end
#implementation MasterViewController
-(void)viewDidAppear:(BOOL)animated
{
//show loader view
//[HUD showUIBlockingIndicatorWithText:#"Fetching JSON"];
//make HTTP call
NSString* searchCall = [NSString stringWithFormat:#"http://www.google.com/calendar/feeds/kao1d80fd2u5kh7268caop11o4%%40group.calendar.google.com/public/full?alt=json"];
[JSONHTTPClient getJSONFromURLWithString: searchCall
completion:^(NSDictionary *json, JSONModelError *err) {
//got JSON back
NSLog(#"Got JSON from web: %#", json);
if (err) {
[[[UIAlertView alloc] initWithTitle:#"Error"
message:[err localizedDescription]
delegate:nil
cancelButtonTitle:#"Close"
otherButtonTitles: nil] show];
return;
}
//initialize the models
events = [CalendarModel arrayOfModelsFromDictionaries:
json[#"feed"][#"entry"]
];
if (events) NSLog(#"Loaded successfully models");
//show the videos
[self.tableView reloadData];
}];
}
;
#pragma mark - table methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return events.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CalendarModel* event = events[indexPath.row];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"yyyy-MM-dd'T'HH:mm:ss.SSSzzz";
NSDate *gmtDate = [formatter dateFromString: [[event.time objectAtIndex:0] startTime]];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
cell.textLabel.text = [NSString stringWithFormat:#"%#",
event.title
];
cell.detailTextLabel.text = [formatter stringFromDate: gmtDate];
return cell;
}
#end
I have found this code online, but he doesn't get data as JSON, but from an iPhone calendar, i believe.
#interface MasterViewController ()
#property (strong, nonatomic) NSMutableDictionary *sections;
#property (strong, nonatomic) NSArray *sortedDays;
#property (strong, nonatomic) NSDateFormatter *sectionDateFormatter;
#property (strong, nonatomic) NSDateFormatter *cellDateFormatter;
- (NSDate *)dateAtBeginningOfDayForDate:(NSDate *)inputDate;
- (NSDate *)dateByAddingYears:(NSInteger)numberOfYears toDate:(NSDate *)inputDate;
#end
#implementation MasterViewController
#synthesize sections;
#synthesize sortedDays;
#synthesize sectionDateFormatter;
#synthesize cellDateFormatter;
- (void)awakeFromNib
{
[super awakeFromNib];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
NSDate *now = [NSDate date];
NSDate *startDate = [self dateAtBeginningOfDayForDate:now];
NSDate *endDate = [self dateByAddingYears:1 toDate:startDate];
EKEventStore *eventStore = [[EKEventStore alloc] init];
NSPredicate *searchPredicate = [eventStore predicateForEventsWithStartDate:startDate endDate:endDate calendars:nil];
NSArray *events = [eventStore eventsMatchingPredicate:searchPredicate];
self.sections = [NSMutableDictionary dictionary];
for (EKEvent *event in events)
{
// Reduce event start date to date components (year, month, day)
NSDate *dateRepresentingThisDay = [self dateAtBeginningOfDayForDate:event.startDate];
// If we don't yet have an array to hold the events for this day, create one
NSMutableArray *eventsOnThisDay = [self.sections objectForKey:dateRepresentingThisDay];
if (eventsOnThisDay == nil) {
eventsOnThisDay = [NSMutableArray array];
// Use the reduced date as dictionary key to later retrieve the event list this day
[self.sections setObject:eventsOnThisDay forKey:dateRepresentingThisDay];
}
// Add the event to the list for this day
[eventsOnThisDay addObject:event];
}
// Create a sorted list of days
NSArray *unsortedDays = [self.sections allKeys];
self.sortedDays = [unsortedDays sortedArrayUsingSelector:#selector(compare:)];
self.sectionDateFormatter = [[NSDateFormatter alloc] init];
[self.sectionDateFormatter setDateStyle:NSDateFormatterLongStyle];
[self.sectionDateFormatter setTimeStyle:NSDateFormatterNoStyle];
self.cellDateFormatter = [[NSDateFormatter alloc] init];
[self.cellDateFormatter setDateStyle:NSDateFormatterNoStyle];
[self.cellDateFormatter setTimeStyle:NSDateFormatterShortStyle];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#pragma mark - Date Calculations
- (NSDate *)dateAtBeginningOfDayForDate:(NSDate *)inputDate
{
// Use the user's current calendar and time zone
NSCalendar *calendar = [NSCalendar currentCalendar];
NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
[calendar setTimeZone:timeZone];
// Selectively convert the date components (year, month, day) of the input date
NSDateComponents *dateComps = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:inputDate];
// Set the time components manually
[dateComps setHour:0];
[dateComps setMinute:0];
[dateComps setSecond:0];
// Convert back
NSDate *beginningOfDay = [calendar dateFromComponents:dateComps];
return beginningOfDay;
}
- (NSDate *)dateByAddingYears:(NSInteger)numberOfYears toDate:(NSDate *)inputDate
{
// Use the user's current calendar
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setYear:numberOfYears];
NSDate *newDate = [calendar dateByAddingComponents:dateComps toDate:inputDate options:0];
return newDate;
}
#pragma mark - UITableViewDataSource methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [self.sections count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSDate *dateRepresentingThisDay = [self.sortedDays objectAtIndex:section];
NSArray *eventsOnThisDay = [self.sections objectForKey:dateRepresentingThisDay];
return [eventsOnThisDay count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSDate *dateRepresentingThisDay = [self.sortedDays objectAtIndex:section];
return [self.sectionDateFormatter stringFromDate:dateRepresentingThisDay];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *reuseIdentifier = #"EventTitleCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
NSDate *dateRepresentingThisDay = [self.sortedDays objectAtIndex:indexPath.section];
NSArray *eventsOnThisDay = [self.sections objectForKey:dateRepresentingThisDay];
EKEvent *event = [eventsOnThisDay objectAtIndex:indexPath.row];
cell.textLabel.text = event.title;
if (event.allDay) {
cell.detailTextLabel.text = #"all day";
} else {
cell.detailTextLabel.text = [self.cellDateFormatter stringFromDate:event.startDate];
}
return cell;
}
#end
Is there a way for me to use my json event.startdate as a section header?
Personally, I would ignore the code you posted second there because its not what you are trying to do.
The part of the code where you set you header and subtitle are these two lines:
cell.textLabel.text = [NSString stringWithFormat:#"%#",event.title];
cell.detailTextLabel.text = [formatter stringFromDate: gmtDate];
So if you want the heading to be the date, just place it as the cell.textLabel.text value.
So if you are wanting to do sections.
Make sure the number of sections is greater then 1.
Then you might want to take a look at these table methods. Just depending on what your exact case and customization needs are you can change it accordingly.
(NSString*) tableView:(UITableView*)tableView titleForHeaderInSection:(NSInteger)section{
}
(CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section{
}
(UIView*)tableView:(UITableView*)table viewForHeaderInSection:(NsInteger)section{
}
I hope this helps. I normally would have an example I just didn't have the most available time currently, but if need be I can provide one.
Take Care :)

iPhone error in delete function

The YApp crashes whenever I press the Delete button from the simulator in iPhone. I have copied some code from my project here. How can I solve the delete bug?
I found a similar question, Error in the delete function of the alarm app in iPhone, but it does not answer my question.
My code is below.
#import "FirstPage.h"
#implementation FirstPage
#synthesize datePicker, eventText,tableview;
- (void) viewWillAppear:(BOOL)animated {
[self.tableview reloadData];
}
- (IBAction) scheduleAlarm:(id) sender {
[eventText resignFirstResponder];
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
// Get the current date
NSDate *pickerDate = [self.datePicker date];
// Break the date up into components
NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit )
fromDate:pickerDate];
NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit )
fromDate:pickerDate];
// Set up the fire time
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:[dateComponents day]];
[dateComps setMonth:[dateComponents month]];
[dateComps setYear:[dateComponents year]];
[dateComps setHour:[timeComponents hour]];
// Notification will fire in one minute
[dateComps setMinute:[timeComponents minute]];
[dateComps setSecond:[timeComponents second]];
NSDate *itemDate = [calendar dateFromComponents:dateComps];
[dateComps release];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = itemDate;
localNotif.timeZone = [NSTimeZone defaultTimeZone];
// Notification details
localNotif.alertBody = [eventText text];
// Set the action button
localNotif.alertAction = #"View";
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;
// Specify custom data for the notification
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:#"someValue" forKey:#"someKey"];
localNotif.userInfo = infoDict;
// Schedule the notification
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];
[self.tableview reloadData];
}
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization.
}
return self;
}
*/
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
[eventText resignFirstResponder];
return YES;
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
Array = [[NSMutableArray alloc]init];
eventText.delegate = self;
[super viewDidLoad];
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
int count = [Array count];
if(self.editing) count++;
//return count;
return [[[UIApplication sharedApplication] scheduledLocalNotifications] count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
NSArray *notificationArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
// notificationArray = Array;
notif = [notificationArray objectAtIndex:indexPath.row];
[cell.textLabel setText:notif.alertBody];
[cell.detailTextLabel setText:[notif.fireDate description]];
return cell;
}
- (IBAction)DeleteButtonAction:(id)sender
{
[Array removeLastObject];
[tableview reloadData];
}
- (IBAction) EditTable:(id)sender
{
if(self.editing)
{
[super setEditing:NO animated:NO];
[tableview setEditing:NO animated:NO];
// [tableview reloadData];
// [self.navigationItem.leftBarButtonItem setTitle:#"Edit"];
// [self.navigationItem.leftBarButtonItem setStyle:UIBarButtonItemStylePlain];
}
else
{
[super setEditing:YES animated:YES];
[tableview setEditing:YES animated:YES];
// [tableview reloadData];
// [self.navigationItem.leftBarButtonItem setTitle:#"Done"];
// [self.navigationItem.leftBarButtonItem setStyle:UIBarButtonItemStyleDone];
}
}
// The editing style for a row is the kind of button displayed to the left of the cell when in editing mode.
- (UITableViewCellEditingStyle)tableView:(UITableView *)aTableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
// No editing style if not editing or the index path is nil.
if (self.editing == NO || !indexPath) return UITableViewCellEditingStyleNone;
// Determine the editing style based on whether the cell is a placeholder for adding content or already
// existing content. Existing content can be deleted.
if (self.editing && indexPath.row == ([Array count]))
{
return UITableViewCellEditingStyleInsert;
} else
{
return UITableViewCellEditingStyleDelete;
}
return UITableViewCellEditingStyleNone;
}
// Update the data model according to edit actions delete or insert.
- (void)tableView:(UITableView *)aTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
[Array removeObjectAtIndex:indexPath.row];
// [tableview reloadData];
} else if (editingStyle == UITableViewCellEditingStyleInsert)
{
}
}
#pragma mark Row reordering
// Determine whether a given row is eligible for reordering or not.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
// Process the row move. This means updating the data model to correct the item indices.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath
toIndexPath:(NSIndexPath *)toIndexPath
{
NSString *item = [[Array objectAtIndex:fromIndexPath.row] retain];
[Array removeObject:item];
[Array insertObject:item atIndex:toIndexPath.row];
[item release];
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc. that aren't in use.
}
- (void)viewDidUnload {
datePicker = nil;
tableview = nil;
eventText = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
#end
I think the problem is in the section listed below.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
int count = [Array count];
if(self.editing) count++;
//return count;
return [[[UIApplication sharedApplication] scheduledLocalNotifications] count];
}

Resources