How to pass value in select UITableViewCell Row - ios

I have UITableViewCell, cell indexing category wise and expand cell click on header, and load data by JSON. I want to select cell and pass data another view controller. I try to many times but pass data only first cell. I clicked another cell so this condition pass data first cell. Can't send particular cell data. How it possible . please help.
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error;
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
NSArray *statuses = [json objectForKey:#"status"];
names=[[NSMutableArray alloc]initWithArray:[statuses valueForKey:#"business_category_name"]];
business_details_array=[[NSMutableArray alloc]initWithArray:[statuses valueForKey:#"business_details"]];
for (int i=0; i<[names count]; i++) {
[arrayForBool addObject:[NSNumber numberWithBool:NO]];
}
[self.tabel_view reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return names.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([[arrayForBool objectAtIndex:section] boolValue]) {
return [[business_details_array objectAtIndex:section] count];
}
else
return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 70;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *sectionHeaderView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width,70)];
sectionHeaderView.backgroundColor=[UIColor grayColor];
sectionHeaderView.tag=section;
UIView *sectionsubHeaderView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width,60)];
sectionsubHeaderView.backgroundColor=[UIColor blueColor];
UIImageView *arrow=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0,60, 60)];
[arrow setImage:[UIImage imageNamed:#"arrow.png"]];
UILabel *Lbl=[[UILabel alloc]initWithFrame:CGRectMake(60, 0,tableView.frame.size.width-60, 60)];
Lbl.text=[names objectAtIndex:section];
Lbl.textColor=[UIColor whiteColor];
[sectionsubHeaderView addSubview:arrow];
[sectionsubHeaderView addSubview:Lbl];
[sectionHeaderView addSubview:sectionsubHeaderView];
UITapGestureRecognizer *headerTapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(sectionHeaderTapped:)];
[sectionHeaderView addGestureRecognizer:headerTapped];
return sectionHeaderView;
}
- (void)sectionHeaderTapped:(UITapGestureRecognizer *)gestureRecognizer
{
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:gestureRecognizer.view.tag];
if (indexPath.row == 0) {
BOOL collapsed = [[arrayForBool objectAtIndex:indexPath.section] boolValue];
for (int i=0; i<[names count]; i++) {
if (indexPath.section==i) {
[arrayForBool replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:!collapsed]];
}
}
[self.tabel_view reloadSections:[NSIndexSet indexSetWithIndex:gestureRecognizer.view.tag] withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MemberTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"ht"];
if (cell==nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"Cell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
NSString*title_str=[NSString stringWithFormat:#"%#",[[[business_details_array objectAtIndex:indexPath.section] valueForKey:#"name"] objectAtIndex:indexPath.row]];
cell.title.text= title_str;
[titles addObject:title_str];
NSLog(#"get %#",titles);
cell.email.text=[NSString stringWithFormat:#"%#",[[[business_details_array objectAtIndex:indexPath.section] valueForKey:#"email"] objectAtIndex:indexPath.row]];
//[emailary addObject:cell.email.text];
cell.address_lbl.text=[NSString stringWithFormat:#"%#",[[[business_details_array objectAtIndex:indexPath.section] valueForKey:#"address"] objectAtIndex:indexPath.row]];
//[adrsary addObject:cell.address_lbl.text];
cell.phone_lbl.text=[NSString stringWithFormat:#"%#",[[[business_details_array objectAtIndex:indexPath.section] valueForKey:#"phone"] objectAtIndex:indexPath.row]];
// [phoneary addObject:cell.phone_lbl.text];
cell.web_lbl.text=[NSString stringWithFormat:#"%#",[[[business_details_array objectAtIndex:indexPath.section] valueForKey:#"website"] objectAtIndex:indexPath.row]];
//[websiteary addObject:cell.web_lbl.text];
cell.sens_lbl.text=[NSString stringWithFormat:#"%#",[[[business_details_array objectAtIndex:indexPath.section] valueForKey:#"member_since"] objectAtIndex:indexPath.row]];
//[sensary addObject:cell.sens_lbl.text];
cell.des_lbl.text=[NSString stringWithFormat:#"%#",[[[business_details_array objectAtIndex:indexPath.section] valueForKey:#"des"] objectAtIndex:indexPath.row]];
//[desary addObject:cell.des_lbl.text];
NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString: [NSString stringWithFormat:#"%#",[[[business_details_array objectAtIndex:indexPath.section] valueForKey:#"img_url"] objectAtIndex:indexPath.row]]]];
UIImage* image = [[UIImage alloc] initWithData:imageData];
cell.image_view.image =image;
//[images addObject:cell.image_view.image];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[arrayForBool replaceObjectAtIndex:indexPath.section withObject:[NSNumber numberWithBool:NO]];
[self.tabel_view reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationAutomatic];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"showRecipeDetail"])
{
NSIndexPath *indexPath = [self.tabel_view indexPathForSelectedRow];
member_details *destViewController = segue.destinationViewController;
destViewController.hello = [titles objectAtIndex:indexPath.row];
}
}

As you have directly joined segue from tableview, it's not proper way to do that. Instead of you have to joined segue by controller to controller. So before getting proper selected row index, your view controller push fast and you are always getting 0 index.
Instead of writing logic in prepareForSegue, you can do the same stuff in didSelect method of UITablView.
For that you have to find your destination view controller from storyboard. And set the data to required property.
EDIT
Remove your prepare segure logic and do this in didSelect
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[arrayForBool replaceObjectAtIndex:indexPath.section withObject:[NSNumber numberWithBool:NO]];
[self.tabel_view reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationAutomatic];
UIStoryboard *storyboard =
[UIStoryboard storyboardWithName:#"MainStoryboard"
bundle:[NSBundle mainBundle]];
YourDestinationVC *vc =[[storyboard instantiateViewControllerWithIdentifier:#"YourDestinationVC"]; //#"YourDestinationVC" is storyboardID for your destination view controller
vc.hello = [titles objectAtIndex:indexPath.row];
[[self navigationController] pushViewController:vc animated:YES];
}
Here is screenshot :

You should create your segues between viewcontrollers.
Do not create segue from cell to viewcontrollers.
Then you should call
[self performSegueWithIdentifier:#"showRecipeDetail" sender:self];
after updating the table in didSelectRowAtIndexPath

Try this remove prepare for prepareForSegue and in didselectrowatindexpath add.
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[arrayForBool replaceObjectAtIndex:indexPath.section withObject:[NSNumber numberWithBool:NO]];
[self.tabel_view reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationAutomatic];
member_details *destViewController = [[member_details alloc]init];
destViewController.hello = [titles objectAtIndex:indexPath.row];
[[self navigationController] pushViewController:destViewController animated:YES];
}

Try This
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self performSegueWithIdentifier:#"showRecipeDetail" sender:[YOUR_ARRAY objectAtIndex:indexPath.row]];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"showRecipeDetail"])
{
member_details *destViewController = segue.destinationViewController;
destViewController.hello = sender;
}
}

Related

Buggy swipe to delete display on one more row after each delete

I'm having a weird issue on UITableView delete action since iOS 11.
Here's the relevant TableView code :
#implementation ChatMessageListViewController(TableView)
#pragma mark - table view datasource/delegate
- (NSArray<UITableViewRowAction *> *) tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
NSMutableArray *rowActions = [NSMutableArray array];
UITableViewRowAction *delete = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:#"Delete" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
[self deleteMessageAtIndexPath:indexPath];
}];
delete.backgroundColor = [UIColor redColor];
[rowActions addObject:delete];
return [rowActions copy];
}
- (void) deleteMessageAtIndexPath:(NSIndexPath *)indexPath {
NSString *threadID = [[self.messageArray objectAtIndex:indexPath.row] objectForKey:#"threadID"];
[self.tableView beginUpdates];
[self.messageArray removeObjectAtIndex:indexPath.row];
[self.tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
[self.tableView endUpdates];
#weakify(self);
[UIUtil showLoadingHudWithText:WELocalString(#"message_remove_thread_loading_text", #"Deleting...", #"删除中...")];
[[AsyncUtil sharedInstance] dispatch_background_network:^{
DBManager *db = [[DBManager alloc] init];
[db deletetableData:[NSString stringWithFormat:#"singleChat WHERE threadID = '%#' ",threadID] ];
[[MemChatThreadMessages sharedInstance] removeThread:threadID];
NSDictionary * result = [Network deleteChatThread:threadID forEmail:[WEUtil getEmail]];
[[AsyncUtil sharedInstance] dispatch_main:^{
[UIUtil hideLoadingHuds];
#strongify(self);
if(self == nil) return ;
if([result[#"result"] isEqualToString:#"success"]){
}else{
[UIUtil showErrorMessage:WELocalString(#"message_remove_thread_error", #"Cannot delete this thread", #"不能删除该会话!")];
}
[self.tableView reloadData];
}];
}];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [self.messageArray count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
NSDictionary *messageInfo = [self.messageArray objectAtIndex:indexPath.row];
if ([(NSString *)[messageInfo objectForKey:#"isAnnouncement"] isEqualToString:#"1"]) {
return 80;
}else if ([[messageInfo objectForKey:#"chatTag"] isValidString]){
return 80;
}else if([self isSpecialMessage:messageInfo]){
return 80;
}else{
return 67;
}
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"message";
if(self.events == nil){
NSDictionary * d = [WEUtil getMyEventListCache];
self.events = [[NSMutableDictionary alloc] init];
for(NSDictionary * eventSummary in d[#"events"]){
NSString * eventID = eventSummary[#"eventid"];
[self.events setObject:eventSummary forKey:eventID];
}
}
UserMessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil){
cell = [[UserMessageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
if(indexPath.row >= [self.messageArray count]){
TERMINATE_WITH_NIL_CELL;
}
NSDictionary *messageInfo = [self.messageArray objectAtIndex:indexPath.row];
if(![self isSpecialMessage:messageInfo]){
[cell configureCellWithMessageDict:messageInfo];
}else{
[cell configureCellWithNewMessageDict:messageInfo withEvents:self.events];
}
return cell;
}
#pragma mark - Navigation
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSDictionary *msgThreadDict = [self.messageArray objectAtIndex:indexPath.row];
if(![self isSpecialMessage:msgThreadDict]){
[self tableView:tableView didSelectNormalRowAtIndexPath:indexPath];
}else{
NSString * event = msgThreadDict[#"event"];
if([event isValidString]){
if([event isEqualToString:#"no_event_messages"]){
[UIUtil showErrorMessage:#"no event id"];
}else{
[BackendTracking trackingWithAction:#"open_special" withLabel:#"threads_list"];
SpecialTopicListViewController * special = [[SpecialTopicListViewController alloc] init];
special.tracking_src = #"tab";
[self.navigationController pushViewController:special animated:YES];
}
}
}
}
-(void) tableView:(UITableView *)tableView didSelectNormalRowAtIndexPath:(NSIndexPath *)indexPath{
NSDictionary *msgThreadDict = [self.messageArray objectAtIndex:indexPath.row];
NSString *threadID = [msgThreadDict objectForKey:#"threadID"];
NSString *jid = [msgThreadDict objectForKey:#"jid"];
[GATracking trackCategory:#"message" withAction:#"thread_list_item_click" withLabel:threadID];
[[MemChatThreadMessages sharedInstance] setCurrentThreadID:threadID];
PrivateMessageViewController * chatVC = [[PrivateMessageViewController alloc] init];
chatVC.threadID = threadID;
chatVC.targetJID = jid;
chatVC.targetName = [msgThreadDict objectForKey:#"name"];
chatVC.unreadMsgNumber = [[self.messageArray objectAtIndex:indexPath.row][#"unreadCnt"] integerValue];
if ([(NSString *)[msgThreadDict objectForKey:#"isGroup"] isEqualToString:#"1"]) {
chatVC.isGroup = YES;
}else{
chatVC.isGroup = NO;
}
chatVC.src = #"list";
WELogInfo(#"click message");
[self.navigationController pushViewController:chatVC animated:YES];
}
#end
With the update and the changes using those trailing swipe actions there is another View appended before each time I delete an entry (until it doesn't work anymore). I've tried disabling the full trail or implementing iOS 11 trailingSwipeActionsConfigurationForRowAtIndexPath but I can't resolve this issue so far.
Do you see something wrong in the code? The main controller code is in another file.
Try reloading after you delete, after this line
[self.tableView endUpdates];
I think you removed the data from messageArray but as you are not reloading just after that so table view count is still 2 and you are reloading inside the block which might be taking time.
And one more thing you already removing data from messageArray, and then removing from db, So if you fail to remove it from db you are showing its not removed but for user it will be removed, as its no longer in message array

UITableViewCell delete does not use proper UITableViewRowAnimation

When a row is deleted it always slides to left no matter what animation value I pass. I would like it to slide up similar to many of the stock apps.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
self.tableData = [][[self.tableData mutableCopy] removeObjectAtIndex:indexPath.row] copy];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];
}
}
Here is the full tableview controller code, it is has a lot in it. That is the reason I didn't post it at first.
#interface FMListViewController ()
#property (strong) NSArray *currentLocations;
#property (assign) BOOL isEditing;
#end
#implementation FMListViewController
- (void)viewDidLoad {
[super viewDidLoad];
UISegmentedControl *viewType = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:#"List", #"Map", nil]];
CGRect viewTypeRect = viewType.frame;
viewTypeRect.size.width = 150.0f;
viewType.frame = viewTypeRect;
viewType.selectedSegmentIndex = 0;
[viewType addTarget:self action:#selector(viewTypeChange:) forControlEvents:UIControlEventValueChanged];
self.navigationItem.titleView = viewType;
self.currentLocations = [[FMLocations sharedManager] allLocations];
//watch for weather updates
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(weatherUpdated) name:#"weatherUpdated" object:nil];
//watch for changes to saved locations
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(locationsUpdated) name:#"locationsUpdated" object:nil];
self.isEditing = NO;
}
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
// this UIViewController is about to re-appear, make sure we remove the current selection in our table view when swiping back occurs
NSIndexPath *tableSelection = [self.tableView indexPathForSelectedRow];
[self.tableView deselectRowAtIndexPath:tableSelection animated:NO];
[self.navigationController setToolbarHidden:YES animated:NO];
}
- (void)viewTypeChange:(UISegmentedControl *)segControl{
NSLog(#"change to map");
[(FMNavController *)[self navigationController] changeViewType];
segControl.selectedSegmentIndex = 0;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)weatherUpdated{
[self.tableView reloadData];
[self.refreshControl endRefreshing];
}
- (void)locationsUpdated{
if(self.isEditing){
self.currentLocations = [[FMLocations sharedManager] savedLocations];
}else{
self.currentLocations = [[FMLocations sharedManager] allLocations];
}
[self.tableView reloadData];
}
#pragma mark - Table Editing Stuff
- (IBAction)toggleEditing:(id)sender{
if(self.isEditing){
self.isEditing = NO;
self.currentLocations = [[FMLocations sharedManager] allLocations];
[self.tableView reloadData];
UIBarButtonItem *newRightItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:#selector(toggleEditing:)];
self.navigationItem.rightBarButtonItem = newRightItem;
[self.tableView setEditing:NO animated:YES];
}else{
self.isEditing = YES;
self.currentLocations = [[FMLocations sharedManager] savedLocations];
[self.tableView reloadData];
UIBarButtonItem *newRightItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(toggleEditing:)];
self.navigationItem.rightBarButtonItem = newRightItem;
[self.tableView setEditing:YES animated:YES];
}
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.row == 0 && [[FMLocations sharedManager] currentLocation] && !self.isEditing){
return NO;
}
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
//add code here for when you hit delete
NSMutableArray *newLocations;
int arrayOffset = 0;
if([[FMLocations sharedManager] currentLocation] && !self.isEditing){
arrayOffset = -1;
}
newLocations = [[[FMLocations sharedManager] savedLocations] mutableCopy];
int itemToRemove = (int)indexPath.row + arrayOffset;
if(itemToRemove < 0 || itemToRemove > [newLocations count]){
NSLog(#"invalid item to remove");
}else{
[newLocations removeObjectAtIndex:itemToRemove];
[[FMLocations sharedManager] saveSavedLocations:[newLocations copy]];
if(self.isEditing){
self.currentLocations = [[FMLocations sharedManager] savedLocations];
}else{
self.currentLocations = [[FMLocations sharedManager] allLocations];
}
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];
}
}
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.row == 0 && [[FMLocations sharedManager] currentLocation] && !self.isEditing){
return NO;
}
return YES;
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{
NSMutableArray *editableLocations = [[[FMLocations sharedManager] savedLocations] mutableCopy];
if(editableLocations && [editableLocations count] > sourceIndexPath.row && [editableLocations count] > destinationIndexPath.row){
NSInteger fromIndex = sourceIndexPath.row;
NSInteger toIndex = destinationIndexPath.row;
id object = [editableLocations objectAtIndex:fromIndex];
[editableLocations removeObjectAtIndex:fromIndex];
[editableLocations insertObject:object atIndex:toIndex];
[[FMLocations sharedManager] saveSavedLocations:[editableLocations copy]];
}
}
#pragma mark - Refresh control action
- (IBAction)doRefreshTable:(id)sender{
[[ForecastManager sharedManager] updateForecasts];
}
#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.
return [self.currentLocations count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//NSLog(#"getting cell");
FMTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"FMLocationCell" forIndexPath:indexPath];
NSDictionary *theLocation = [self.currentLocations objectAtIndex:indexPath.row];
// Configure the cell...
cell.locationLabel.text = [[theLocation objectForKey:#"name"] uppercaseString];
WeatherObject *locationWeather = [[ForecastManager sharedManager] weatherObjectForLocation:[[theLocation objectForKey:#"id"] intValue]];
[cell setCurrentTemp:locationWeather.currentTemp];
[cell configureForecastViews:locationWeather.forecastObjects];
[cell.weatherPreviewContainer setNeedsDisplay];
return cell;
}
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
if([segue.identifier isEqualToString:#"showLocation"]){
FMDetailViewController *detailController = [segue destinationViewController];
NSDictionary *theLocation = [self.currentLocations objectAtIndex:self.tableView.indexPathForSelectedRow.row];
detailController.navigationItem.title = [theLocation objectForKey:#"name"];
detailController.detailLocation = theLocation;
}
}
You can try below solutions:
1) Replace your line with the below one
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationTop];
2) Change the code with the below one:
[self.tableView beginUpdates];
[self.tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationTop];
[self.tableView endUpdates];
Hope this helps!
please try with that
don't delete cell directly first make its cellheight to zero using. NSIndexPath *deleteIndexPath;
wirte below code before delete
[tbl beginUpdates];
deleteIndexPath = indexPath;
[tbl reloadRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
[tbl endUpdates];
and in set hight method use
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{ if (indexPath == deleteIndexPath) {
return 0;
}
return 50;
}

Select All,Deselect All and select particular cell in custom table view

I have created a drop-down using table cell,where i am showing my data. My data is get display in drop down.Now I want all the cell should be selected initially. Also I want to deselect all cell, and individual cell.
(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([tableView isEqual:expansionTableView]) {
forState:UIControlStateNormal];
if (indexPath.row == 0) {
if ([indexPath isEqual:self.selectIndex]) {
self.isOpen = NO;
[self didSelectCellRowFirstDo:NO nextDo:NO];
self.selectIndex = nil;
}else
{
if (!self.selectIndex) {
self.selectIndex = indexPath;
[self didSelectCellRowFirstDo:YES nextDo:NO];
}else
{
[self didSelectCellRowFirstDo:NO nextDo:YES];
}
}
}else
{
objectForKey:#"surveyName"];
NSMutableArray *list=[[NSMutableArray alloc]init];
NSMutableArray *idlist =[[NSMutableArray alloc]init];
for (int i=0; i<_arraySurveyName.count; i++) {
NSMutableDictionary *dict=[_arraySurveyName objectAtIndex:i];
NSString *surveyName=[dict valueForKey:#"SurveyName"];
NSString *surveyID =[dict valueForKey:#"SurveyId"];
[list addObject:surveyName];
[idlist addObject:surveyID];
}
NSString *item = [list objectAtIndex:indexPath.row-1];
NSNumber *item1= [idlist objectAtIndex:indexPath.row-1];
str = item1;
NSLog(#"%#",str);
[_btn_surveyName setTitle:item forState:UIControlStateNormal];
[expansionTableView setHidden:YES];
}
}
else if ([tableView isEqual:expansionTableViewQtn]){
NSString *selectedQuestion=[arrayOfQuestionDetail objectAtIndex:indexPath.section];
[expansionTableViewQtn setHidden:YES];
[_btn_showQuestn setTitle:selectedQuestion forState:UIControlStateNormal];
}
}
it's my code for "didSelect".How to do this.
You can use below methods to select and deselect the cells
- (void)selectRowAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated scrollPosition:(UITableViewScrollPosition)scrollPosition;
- (void)deselectRowAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated;
[tableView deselectRowAtIndexPath:indexPath animated:NO];//For deselecting
[tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];//For selecting

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);
}

dynamically get the height for the cell depend on UIImageView

I have some pictures.My tableview will load them and change the height of row depend on picture's height.My picture's size is different.
- (void)viewDidLoad
{
NSString *imageName=[kDataArray objectAtIndex:(arc4random()%[kDataArray count])];
UIImageView *importIMG=[[UIImageView alloc]initWithImage:[UIImage imageNamed:imageName]];
//init tablexiewcell
arrayList=[[NSMutableArray alloc] initWithCapacity:kRowsInitSize];
for (NSUInteger i=0; i<kRowsInitSize; i++) {
[arrayList addObject:[kDataArray objectAtIndex:rand()%2]];
}
[TableView setPullToRefreshHandler:^{
NSArray * newRows=[NSArray arrayWithObject:[kDataArray objectAtIndex:rand()%2]];
[self performSelector:#selector(dataDidRefresh:) withObject:newRows afterDelay:3.0];
}];
[super viewDidLoad];
}
#pragma mark- UITableViewDataSource
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
MyCell* cell=[self tableView:tableView cellForRowAtIndexPath:indexPath];
NSLog(#"%f",cell.Pimage.frame.size.height);
return cell.Pimage.frame.size.height;
}
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [arrayList count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
NSString *imageName=[kDataArray objectAtIndex:(arc4random()%[kDataArray count])];
UIImageView *importIMG=[[UIImageView alloc]initWithImage:[UIImage imageNamed:imageName]];
MyCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell==nil) {
cell = [[[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.Pimage=importIMG;
}
return cell;
}
#pragma mark - Private methods
-(void)dataDidRefresh:(NSArray *)data
{
[TableView refreshFinished];
NSIndexSet * indexSet=[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [data count]) ];
NSLog(#"%d",[data count]);
[arrayList insertObjects:data atIndexes:indexSet];
NSMutableArray * indexPaths=[[NSMutableArray alloc] initWithCapacity:[data count]];
for (NSUInteger i=0; i<[data count]; i++)
{
[indexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]];
}
[TableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationTop];
[indexPaths release];
}
I wrote these codes,but i didn't achieve my goal.How can I code it?Please give me help!!!

Resources