Expand UITableViewCell with smooth animation - ios

I am trying to Animate the transition of a UITableViewCell when its height is changed. For this I am using the following lines of code:
[meetingsTable beginUpdates];
[meetingsTable reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:changedRow inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
[meetingsTable endUpdates];
but it is not showing the row height change animation. It just displays the expanded cell. However, if I remove the line
[meetingsTable reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:changedRow inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
it shows the expected animated height change but the cell is not reloaded. I have tried all the available UITableViewRowAnimationoptions but with no success. I have also tried
[meetingsTable reloadData];
but it is also not helpful.
Please suggest what can be the possible solution.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
BMeetingsTableCell *cell;
cell = [tableView dequeueReusableCellWithIdentifier:#"MEETINGS"];
if (!cell) {
cell = [[BMeetingsTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"MEETINGS"];
}
[self customizeCell:cell atIndexPath:indexPath forTable:tableView];
return cell;
}
- (void)customizeCell:(BMeetingsTableCell *)cell atIndexPath:(NSIndexPath *)indexPath forTable:(UITableView*)tableView shouldReload:(BOOL)shouldReload{
NSDictionary *event;
if (isSearching) {
event = [NSDictionary dictionaryWithDictionary:[searchedData objectAtIndex:indexPath.row]];
}else if ([tableView isEqual:_activeMeetingsTable])
event = [NSDictionary dictionaryWithDictionary:[activeEvents objectAtIndex:indexPath.row]];
else if ([tableView isEqual:_completedMeetingTable])
event = [NSDictionary dictionaryWithDictionary:[completedEvents objectAtIndex:indexPath.row]];
NSArray *partArr;
UILabel *showTimeLbl = (UILabel *)[cell viewWithTag:9];
UIImageView *showNewMeetingIcon = (UIImageView *)[cell viewWithTag:8];
[showTimeLbl setHidden:YES];
[showNewMeetingIcon setHidden:YES];
cell.delegate = self;
cell.tag = indexPath.row;
NSMutableArray* foundConts = [[NSMutableArray alloc]init];
NSMutableArray *tempPartArr = [[NSMutableArray alloc]init];
for (NSDictionary *dict in [event valueForKey:#"users"]) {
[tempPartArr addObject:dict];
}
partArr = [NSArray arrayWithArray:tempPartArr];
if ([displayName length]==0) displayName = numberString;
NSDictionary *participant = [[NSDictionary alloc]initWithObjectsAndKeys:inviteStat, #"inviteStatus", displayName, #"displayName", nil];
[foundConts addObject:participant];
}
}
if ([allParticipants count]> indexPath.row) {
[allParticipants replaceObjectAtIndex:indexPath.row withObject:invitedConts];
}else
[allParticipants addObject:invitedConts];
if ([tableView isEqual:_meetingsTable] && selectedRow == indexPath.row) {
cell.participants = [NSArray arrayWithArray:foundConts];
[cell.contsTable setHidden:NO];
// [cell.arrowButton setSelected:YES];
[cell.userImage setImage:[UIImage imageNamed:#"expandedProfilePic.png"]];
}else{
[cell.userImage setImage:[UIImage imageNamed:#"ProfileImage.png"]];
[cell.contsTable setHidden:YES];
// [cell.arrowButton setSelected:NO];
}
[cell.tapProfileBtn addTarget:self action:#selector(expandDetails:) forControlEvents:UIControlEventTouchUpInside];
cell.tapProfileBtn.tag = indexPath.row;
[cell.title setText:[event valueForKey:#"subject"]];
NSString* location;
if ([[event valueForKey:#"address"] isKindOfClass:[NSNull class]]) {
location = #"";
}else
location = [event valueForKey:#"location"];
long long startDateMilliSec = [[event valueForKey:#"start_time_milliseconds"] longLongValue];
NSDate *capturedStartDate = [NSDate dateWithTimeIntervalSince1970:startDateMilliSec];
//
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateStyle:NSDateFormatterFullStyle];
NSDateComponents *comps1 = [[NSCalendar currentCalendar] components:NSYearCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit fromDate:capturedStartDate];
NSString *theYear = [NSString stringWithFormat:#", %ld", (long)comps1.year];
[dateFormatter setDoesRelativeDateFormatting:YES];
[dateFormatter setLocale:[NSLocale currentLocale]];
NSString *dateString = [dateFormatter stringFromDate:capturedStartDate];
if ([dateString isEqualToString:#"Today"]||[dateString isEqualToString:#"Tomorrow"]) {
}else{
[dateFormatter setDateFormat:#"dd MMMM yyyy"];
[dateFormatter setDoesRelativeDateFormatting:NO];
dateString = [dateFormatter stringFromDate:capturedStartDate];
}
NSString *amPM = (comps1.hour>=12)?#"PM":#"AM";
NSString *hourStr = [NSString stringWithFormat:#"%02d",(comps1.hour%12)];
dateString = [dateString stringByReplacingOccurrencesOfString:theYear withString:#""];
NSString *timeString = [NSString stringWithFormat:#"%#:%02d %#",hourStr, comps1.minute, amPM];
NSString *displayString = [NSString stringWithFormat:#"%# | %#",dateString, timeString];
[cell.date setText:[NSString stringWithFormat:#"%# | %#", displayString, location]];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.row == selectedRow) {
NSDictionary* event = [activeEvents objectAtIndex:indexPath.row];
NSArray *contacts = [event valueForKey:#"users"];
int height = ([contacts count]*50)+70;
return height;
}
else return 50
}
- (IBAction)expandDetails:(id)sender{
UIButton *btn = (UIButton*)sender;
selectedRow = btn.tag;
BMeetingsTableCell *changedCell = (BMeetingsTableCell*)[_activeMeetingsTable cellForRowAtIndexPath:[NSIndexPath indexPathForRow:btn.tag inSection:0]];
[self customizeCell:changedCell atIndexPath:[NSIndexPath indexPathForRow:btn.tag inSection:0] forTable:_meetingsTable];
[_meetingsTable beginUpdates];
[_meetingsTable endUpdates];
}

You have to update the cell without reloading the table view.
I imagine you have your cell customization code in cellForRowAtIndexPath.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//dequeue cell
//customize cell at index path
return cell;
}
Move your customization into its own method that takes a cell.
- (void)customizeCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
//customize cell
}
Now when you need to update a cell you can do this...
- (void)rowWasChanged:(NSInteger)changedRow {
NSIndexPath *changedIndex = [NSIndexPath indexPathForRow:changedRow inSection:0];
UITableViewCell *changedCell = [self.meetingsTable cellForRowAtIndexPath:changedIndex];
[self customizeCell:changedCell atIndexPath:changedIndex];
[self.meetingsTable beginUpdates];
[self.meetingsTable endUpdates];
}

// Cell animation
if(sender.tag == 0) {
if(sender.on){
rowHeight1 = 250;
}else{
rowHeight1 = 55;
}
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:sender.tag inSection:0];
NSArray* rowsToReload = [NSArray arrayWithObjects:indexPath, nil];
[tblHealthQuestion reloadRowsAtIndexPaths:rowsToReload withRowAnimation:UITableViewRowAnimationAutomatic];
}
// for Section animation
NSRange range = NSMakeRange(senctionIndex, 1);//NSMakeRange(0, 1);
NSIndexSet *section = [NSIndexSet indexSetWithIndexesInRange:range];
[tblHealthQuestion reloadSections:section withRowAnimation:UITableViewRowAnimationAutomatic];
- (void)reloadSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation{
[self reloadSections:sections withRowAnimation:animation];
}

Related

UITableView row order

I have a strange behavior my tableView
I make dropdown section on my tableView. It's look like:
but if I reopen my section rows order was ather like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
NSLog(#"CURRENT ROW = %ld", (long)indexPath.row);
UILabel *titleLable = [[UILabel alloc] initWithFrame:CGRectMake(90, 20, cell.frame.size.width - 90, 20)];
titleLable.text = [NSString stringWithFormat:#"урок %ld", (long)indexPath.row];
[cell addSubview:titleLable];
UILabel *percentLable = [[UILabel alloc] initWithFrame:CGRectMake(cell.frame.size.width - 40, 20, 50, 20)];
LessonModel *lesson = [self.lessonsArray objectAtIndex:indexPath.section];
NSArray *childrenArrey = [[NSArray alloc] initWithArray:(NSArray *) lesson.childrenArray];;
percentLable.text =[NSString stringWithFormat:#"%# %%", [childrenArrey[indexPath.row] valueForKey:#"percent"]];
[cell addSubview:percentLable];
}
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
LessonModel *lesson = [self.lessonsArray objectAtIndex:indexPath.section];
NSArray *childrenArrey = [[NSArray alloc] initWithArray:(NSArray *) lesson.childrenArray];
NSString *uid = [childrenArrey[indexPath.row] valueForKey:#"id"];
[self makeLessonWithId:uid];
}
- (void)sectionHeaderTapped:(UITapGestureRecognizer *)gestureRecognizer{
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:gestureRecognizer.view.tag];
if (indexPath.row == 0) {
BOOL collapsed = [[self.arrayForBool objectAtIndex:indexPath.section] boolValue];
collapsed = !collapsed;
[self.arrayForBool replaceObjectAtIndex:indexPath.section withObject:[NSNumber numberWithBool:collapsed]];
[self updateLabelFrame:gestureRecognizer.view.tag];
NSRange range = NSMakeRange(indexPath.section, 1);
NSIndexSet *sectionToReload = [NSIndexSet indexSetWithIndexesInRange:range];
[self.tableView reloadSections:sectionToReload withRowAnimation:UITableViewRowAnimationFade];
}
}
Try by putting values in else part too:
if (cell == nil){
//your code as it is
}
else{
titleLable.text = [NSString stringWithFormat:#"урок %ld", (long)indexPath.row];
NSArray *childrenArrey = [[NSArray alloc] initWithArray:(NSArray *) lesson.childrenArray];;
percentLable.text =[NSString stringWithFormat:#"%# %%", [childrenArrey[indexPath.row] valueForKey:#"percent"]];
}

Objective-C: Change UIImageView in Custom Cell change different cell images

I am using a custom cell on UITableView with multi Section and i’m added a UITapGestureRecognizer to a UIImageView for change it when the image is selected but When I select the image other's images in different cell are selected as well.
This is the code for the TableView datasource method cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"FilterCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
UILabel *text = (UILabel *)[cell viewWithTag:ROW_TITLE];
UIImageView *image = (UIImageView *)[cell viewWithTag:ROW_IMAGE];
NSDictionary *item = [results objectAtIndex:indexPath.section];
NSString *string = [item objectForKey:JSONResp_common_name];
[text setText:((string != [NSNull null])? string : #"")];
if ([[item objectForKey:JSONResp_common_status] isEqualToNumber:[NSNumber numberWithBool:YES]])
[image setImage:[UIImage imageNamed:#"checked"]];
else
[image setImage:[UIImage imageNamed:#"unchecked"]];
UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
[image setTag:indexPath.row];
[image setUserInteractionEnabled:YES]; action:#selector(handleTapFrom:)];
if([self tableView:tableView
canCollapseSection:indexPath.section]){ // EXPANDABLE ROW
if(!indexPath.row){// HEADER
// SET ACCESORIES
if([expandedSections containsIndex:indexPath.section])
[cell setAccessoryView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"menos"]]];
else
[cell setAccessoryView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"mas"]]];
[image setUserInteractionEnabled:NO];
//Remove checked option from a cell
for(UITapGestureRecognizer *tapGesture in cell.gestureRecognizers)
[cell removeGestureRecognizer:tapGesture];
}else{// SUB ROWS
NSArray *subValues = [item objectForKey:PARAM_STRUCT_SUBELEMENTS];
NSDictionary *detail = [subValues objectAtIndex:indexPath.row -1];
//REASING VALUES TO SUB VALUES
if(detail && [detail isKindOfClass:[City class]]){
City *currentCity = (City *)detail;
[text setText:[currentCity name]];
}
[cell setAccessoryView:nil];
[tapGestureRecognizer setDelegate:self];
[cell addGestureRecognizer:tapGestureRecognizer];
}
}else{//ROWS CHECKED OPTION
[cell setAccessoryView:nil];
[tapGestureRecognizer setDelegate:self];
[cell addGestureRecognizer:tapGestureRecognizer];
}
return cell;
}
</code>
</pre>
This is the code for the TableView datasource method didSelectRowAtIndexPath:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSDictionary *data = [self.results objectAtIndex:indexPath.section];
if([self tableView:tableView
canCollapseSection:indexPath.section]){
if(!indexPath.row){// EXPANDABLE
// only first row toggles expandaed/collapse
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSInteger section = indexPath.section;
BOOL currentlyExpanded = [expandedSections containsIndex:section];
NSInteger rows;
NSMutableArray *tmpArray = [NSMutableArray array];
if(currentlyExpanded){
rows = [self tableView:tableView
numberOfRowsInSection:section];
[expandedSections removeIndex:section];
}else{
[expandedSections addIndex:section];
rows = [self tableView:tableView
numberOfRowsInSection:section];
}
for(int i = 1; i < rows; i++){
NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i
inSection:section];
[tmpArray addObject:tmpIndexPath];
}
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if(currentlyExpanded){
[tableView deleteRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"mas"]];
}else{
[tableView insertRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"menos"]];
}
}else{// Detail
}
}else{ // Normal Row
//[]
}}
This is the code for the TableView datasource method fro the UITapGestureRecognizer
- (void)handleTapFrom:(UITapGestureRecognizer *)recognizer {
UITableViewCell *cellView = (UITableViewCell *)[recognizer view];
UIImageView *switchImageView = nil;
for (UIView *item in [[[cellView subviews] firstObject] subviews]) {
if ([item isKindOfClass:[UIImageView class]] && ((UIImageView *)item).image != nil) {
switchImageView = (UIImageView *)item;
break;
}
}
if (switchImageView == nil) {
for (UIView *item in [[[[[cellView subviews] firstObject] subviews] objectAtIndex:1] subviews]) {
if ([item isKindOfClass:[UIImageView class]] && ((UIImageView *)item).image != nil) {
switchImageView = (UIImageView *)item;
break;
}
}
}
NSDictionary *item = [results objectAtIndex:switchImageView.tag];
if ([Utility image:switchImageView.image
isEqualTo:[UIImage imageNamed:IMAGE_UNCHECKED]]) {
if ([[item objectForKey:JSONResp_common_action] isEqualToString:JSONResp_sortings]) {
[delegate didCheckFilter:item
withStatus:YES];
} else if ([[item objectForKey:JSONResp_common_action] isEqualToString:JSONResp_filters]) {
[switchImageView setImage:[UIImage imageNamed:IMAGE_CHECKED]]; //change to a selected image
[delegate didCheckFilter:[item objectForKey:JSONResp_common_type]
withStatus:YES];
}
} else {
if ([[item objectForKey:JSONResp_common_action] isEqualToString:JSONResp_filters]) {
[switchImageView setImage:[UIImage imageNamed:IMAGE_UNCHECKED]];
[delegate didCheckFilter:[item objectForKey:JSONResp_common_type]
withStatus:NO];
}
}}
While declaring the UITapGestureRecognizer on particular cell assign the tag as
cell.tag = indexPath.row;
[cell addGestureRecognizer:tapGestureRecognizer];
and in your handler do like this
- (void)handleTapFrom:(UITapGestureRecognizer *)recognizer {
UITableViewCell *cellView = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:recognizer.tag inSection:0]];
// your stuff
}
Hope this Helps!

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

Replacing one NSMutableDictionary object in NSMutableArray, replaces all objects

I am fairly knew to iOS development and I think I jumped into the deep end too fast.
I am trying to replace a NSMutableDictionary inside an NSMutableArray of dictionaries by using replaceObjectAtIndex:withObject: but when I reload my tableView, all the objects in the array have been replaced by the one I am trying to replace,not just the specific index.
Thanks in advance for your help.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
}
if ((self.editing && indexPath.row == [detailsArray count])) {
cell.textLabel.text = #"Add Detail";
return cell;
}
[cell.textLabel setText:[[detailsArray objectAtIndex:indexPath.row] objectForKey:#"name"]];
[cell.detailTextLabel setText:[[detailsArray objectAtIndex:indexPath.row] objectForKey:#"desc"]];
return cell;
}
-(void)setEditing:(BOOL)editing animated:(BOOL)animated{
[super setEditing:editing animated:animated];
[self.tableView setEditing:editing animated:animated];
if (!editing) {
[dictionaryList setValue:name.text forKey:#"name"];
[dictionaryList setValue:description.text forKey:#"desc"];
[detailsArray replaceObjectAtIndex:IndexHelper.row withObject:dictionaryList];
}
[self.tableView reloadData];
}
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
// 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
if ([detailsArray count] > 0) {
[detailsArray removeObjectAtIndex:indexPath.row];
[tableView beginUpdates];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationFade];
[tableView endUpdates];
}
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
[dictionaryList setValue:#"Title" forKey:#"name"];
[dictionaryList setValue:#"Details" forKey:#"desc"];
[detailsArray addObject:dictionaryList];
[[self tableView] endUpdates];
[[self tableView] insertRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationFade];
[[self tableView] endUpdates];
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
IndexHelper = indexPath;
UIAlertView *passwordAlert = [[UIAlertView alloc] initWithTitle:#"" message:#"\n\n\n\n"
delegate:self cancelButtonTitle:#"Άκυρο" otherButtonTitles:#"Αποθήκευση", nil];
UIImageView *passwordImage = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"passwordfield" ofType:#"png"]]];
passwordImage.frame = CGRectMake(11,20,262,33);
[passwordAlert addSubview:passwordImage];
name = [[UITextField alloc] initWithFrame:CGRectMake(16,25,252,21)];
name.font = [UIFont systemFontOfSize:18];
name.backgroundColor = [UIColor whiteColor];
name.secureTextEntry = NO;
name.keyboardAppearance = UIKeyboardAppearanceAlert;
name.delegate = self;
name.placeholder = #"Title";
[name becomeFirstResponder];
[passwordAlert addSubview:name];
UIImageView *passwordImage2 = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"passwordfield" ofType:#"png"]]];
passwordImage2.frame = CGRectMake(11,65,262,33);
[passwordAlert addSubview:passwordImage2];
description = [[UITextField alloc] initWithFrame:CGRectMake(16,70,252,21)];
description.font = [UIFont systemFontOfSize:18];
description.backgroundColor = [UIColor whiteColor];
description.secureTextEntry = NO;
description.keyboardAppearance = UIKeyboardAppearanceAlert;
description.delegate = self;
description.placeholder = #"Details";
[description becomeFirstResponder];
[passwordAlert addSubview:description];
[passwordAlert show];
}
---This is where I am replacing the dictionary in the array---
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
if (buttonIndex==1) {
if ([name.text isEqualToString:#""] && [description.text isEqualToString:#""]) {
return;
}
[dictionaryList setValue:name.text forKey:#"name"];
[dictionaryList setValue:description.text forKey:#"desc"];
[detailsArray replaceObjectAtIndex:indexPath.row withObject:dictionaryList];
}
[self.tableView reloadData];
NSLog(#"%#",detailsArray);
}
I think you are adding same dictionary at all the indexes to it takes a common reference you have to check and make multiple instances for the dictionary for each index.
It may help you
I think the problem lies in the first of the code below
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
//NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow]; //REMOVE THIS LINE
NSIndexPath *indexPath = IndexHelper; //USE THIS LINE
if (buttonIndex==1) {
if ([name.text isEqualToString:#""] && [description.text isEqualToString:#""]) {
return;
}
[dictionaryList setValue:name.text forKey:#"name"];
[dictionaryList setValue:description.text forKey:#"desc"];
[detailsArray replaceObjectAtIndex:indexPath.row withObject:dictionaryList];
}
[self.tableView reloadData];
NSLog(#"%#",detailsArray);
}

tableView and how to correctly use "Load more..."

I'm have kind of a really small and annoying problem. (No pun intended)
I kind seem to find my mistake. I also asked in chat, but we couldn't find the solution. I got the "Load more..." for my tableView from Abizerns github and implemented it. It works, except for the part, that when it starts up I have to click "Load more...". So on start it doesn't show me the first entries of the tableView until I clicked on "Load more...". You can see my annoyance. Maybe someone can spot my mistake, so that the tableView actually loads the first ten entries on start up.
#define kNumberOfItemsToAdd 10
#define PADDING 10.0f
#interface Main ()
#end
#implementation Main
#synthesize tabelle;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
numberOfItemsToDisplay = kNumberOfItemsToAdd;
return self;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if (numberOfItemsToDisplay == [tabelle count]) {
return 1;
}
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section == 0) {
return numberOfItemsToDisplay;
} else {
return 1;
}
}
- (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];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 6;
cell.detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.detailTextLabel.numberOfLines = 1;
}
if (indexPath.section == 0) {
cell.textLabel.font = [UIFont fontWithName:#"Verdana" size:14.0];
cell.detailTextLabel.font = [UIFont fontWithName:#"Verdana" size:12.0];
NSString *TableText = [[NSString alloc] initWithFormat:#"%#", [[tabelle objectAtIndex:indexPath.row] Name]];
NSString *TableText2 = [[NSString alloc] initWithFormat:#"%#", [[tabelle objectAtIndex:indexPath.row] m_m]];
NSString *cellValue = [NSString stringWithFormat:#"%#", TableText2];
NSString *cellValue2 = [NSString stringWithFormat:#"by: %#", TableText];
cell.textLabel.text = cellValue;
cell.detailTextLabel.textColor = [UIColor colorWithRed:0.196f green:0.3098f blue:0.52f alpha:1.f];
cell.detailTextLabel.text = cellValue2;
} else {
cell.textLabel.text = [NSString stringWithFormat:#"Next %d items", kNumberOfItemsToAdd];
cell.textLabel.textAlignment = UITextAlignmentCenter;
cell.textLabel.textColor = [UIColor colorWithRed:0.196f green:0.3098f blue:0.52f alpha:1.f];
cell.textLabel.font = [UIFont boldSystemFontOfSize:14.f];
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *text = [[self.tabelle objectAtIndex:indexPath.row] m_m];
CGSize textSize = [text sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:CGSizeMake(self.tableView.frame.size.width - PADDING * 3, 1000.0f)];
return textSize.height + PADDING * 3;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 1) {
NSUInteger i, totalNumberOfItems = [tabelle count];
NSUInteger newNumberOfItemsToDisplay = MIN(totalNumberOfItems, numberOfItemsToDisplay + kNumberOfItemsToAdd);
NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
for (i=numberOfItemsToDisplay; i<newNumberOfItemsToDisplay; i++) {
[indexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]];
}
numberOfItemsToDisplay = newNumberOfItemsToDisplay;
[tableView beginUpdates];
[tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationTop];
if (numberOfItemsToDisplay == totalNumberOfItems) {
[tableView deleteSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationTop];
}
[tableView endUpdates];
// Scroll the cell to the top of the table
if (newNumberOfItemsToDisplay < totalNumberOfItems) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 200000000), dispatch_get_main_queue(), ^(void){
[tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
});
[tableView deselectRowAtIndexPath:indexPath animated:YES];
} else {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 200000000), dispatch_get_main_queue(), ^(void){
[tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:totalNumberOfItems-1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
});
}
}
}
I haven't used a "Load more..." implementation, but maybe what you need is add [self.tabelle reloadData] in your - (void)viewWillAppear:(BOOL)animated method.
What method gets called when you click "Load more..."? Can you not programmatically call that method when the tableview is loaded?

Resources