I used the amended DateCell code from the following link DateCell without storyboard.
I want to replace UIDatePicker with UIPickerView. Below is the code that I have amended/commented to make it work for UIPickerView.
On each cell tap, I'm able to show UIPickerView but it only loads once and for the rest of the cells UIPickerView with same row titles appears and it crashes when I select a row from UIPickerView. I'm stuck into this for last couple of days.
Any help would be highly appreciated.
MoreTableViewController.h
#import <UIKit/UIKit.h>
#interface MoreTableViewController : UITableViewController<UIPickerViewDataSource, UIPickerViewDelegate>
#property(nonatomic,retain)NSArray *ASOR;
#property(nonatomic,retain)NSArray *ASQT;
#property(nonatomic,retain)NSArray *respectiveOptions;
#end
MoreTableViewController.m
#import "MoreTableViewController.h"
#import "AppDelegate.h"
#define kPickerAnimationDuration 0.40 // duration for the animation to slide the date picker into view
#define kDatePickerTag 99 // view tag identifiying the date picker view
//#define kTitleKey #"title" // key for obtaining the data source item's title
//#define kDateKey #"date" // key for obtaining the data source item's date value
// keep track of which rows have date cells
#define kDateStartRow 1
#define kDateEndRow 2
static NSString *kDateCellID = #"dateCell"; // the cells with the start or end date
static NSString *kDatePickerID = #"datePicker"; // the cell containing the date picker
static NSString *kOtherCell = #"otherCell"; // the remaining cells at the end
#pragma mark -
#interface MoreTableViewController ()
#property (nonatomic, strong) NSArray *dataArray;
//#property (nonatomic, strong) NSDateFormatter *dateFormatter;
// keep track which indexPath points to the cell with UIDatePicker
#property (nonatomic, strong) NSIndexPath *datePickerIndexPath;
#property (assign) NSInteger pickerCellRowHeight;
#property (nonatomic, strong) UIPickerView *pickerView;
#end
#implementation MoreTableViewController
#synthesize ASOR, ASQT, respectiveOptions;
- (UITableViewCell *) createCellWithIdetifier:(NSString *)cellId {
NSArray *reusableUiComponents = [[NSBundle mainBundle] loadNibNamed:#"ReusableUIComponents" owner:self options:nil];
if ([kDateCellID isEqualToString:cellId]) {
return reusableUiComponents[0];
}
if ([kDatePickerID isEqualToString:cellId]) {
return reusableUiComponents[1];
}
// if ([kOtherCell isEqualToString:cellId]) {
// return reusableUiComponents[2];
// }
return nil;
}
- (AppDelegate *)appDelegate {
return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)setupDataSource {
// setup our data source
// NSMutableDictionary *itemOne = [#{ kTitleKey : #"Tap a cell to change its date:" } mutableCopy];
// NSMutableDictionary *itemTwo = [#{ kTitleKey : #"Start Date",
// kDateKey : [NSDate date] } mutableCopy];
// NSMutableDictionary *itemThree = [#{ kTitleKey : #"End Date",
// kDateKey : [NSDate date] } mutableCopy];
// NSMutableDictionary *itemFour = [#{ kTitleKey : #"(other item1)" } mutableCopy];
// NSMutableDictionary *itemFive = [#{ kTitleKey : #"(other item2)" } mutableCopy];
self.dataArray = [[self appDelegate]advanceSearchQuestionsText];
//self.dateFormatter = [[NSDateFormatter alloc] init];
//[self.dateFormatter setDateStyle:NSDateFormatterShortStyle]; // show short-style date format
//[self.dateFormatter setTimeStyle:NSDateFormatterNoStyle];
// obtain the picker view cell's height, works because the cell was pre-defined in our storyboard
UITableViewCell *pickerViewCellToCheck = [self createCellWithIdetifier:kDatePickerID];
self.pickerCellRowHeight = pickerViewCellToCheck.frame.size.height;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self setupDataSource];
//self.title = #"DateCell";
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
ASQT = [[NSArray alloc]init];
ASOR = [[NSArray alloc]init];
ASQT = [[self appDelegate]advanceSearchQuestionsText];
ASOR = [[self appDelegate]advanceSearchOptionsArray];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Utilities
/*! Returns the major version of iOS, (i.e. for iOS 6.1.3 it returns 6)
*/
NSUInteger UNUSED_DeviceSystemMajorVersion() // TODO - move this to Utils
{
static NSUInteger _deviceSystemMajorVersion = -1;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_deviceSystemMajorVersion = [[[[[UIDevice currentDevice] systemVersion] componentsSeparatedByString:#"."] objectAtIndex:0] intValue];
});
return _deviceSystemMajorVersion;
}
/*! Determines if the given indexPath has a cell below it with a UIDatePicker.
#param indexPath The indexPath to check if its cell has a UIDatePicker below it.
*/
- (BOOL)hasPickerForIndexPath:(NSIndexPath *)indexPath
{
BOOL hasDatePicker = NO;
NSInteger targetedRow = indexPath.row;
targetedRow++;
UITableViewCell *checkDatePickerCell =
[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:targetedRow inSection:0]];
UIPickerView *checkDatePicker = (UIPickerView *)[checkDatePickerCell viewWithTag:kDatePickerTag];
hasDatePicker = (checkDatePicker != nil);
return hasDatePicker;
}
/*! Updates the UIDatePicker's value to match with the date of the cell above it.
*/
- (void)updateDatePicker
{
if (self.datePickerIndexPath != nil)
{
UITableViewCell *associatedDatePickerCell = [self.tableView cellForRowAtIndexPath:self.datePickerIndexPath];
UIPickerView *targetedDatePicker = (UIPickerView *)[associatedDatePickerCell viewWithTag:kDatePickerTag];
if (targetedDatePicker != nil)
{
// we found a UIDatePicker in this cell, so update it's date value
//
// NSDictionary *itemData = self.dataArray[self.datePickerIndexPath.row - 1];
// [targetedDatePicker setDate:[itemData valueForKey:kDateKey] animated:NO];
// set the call action for the date picker to dateAction
// [targetedDatePicker addTarget:self action:#selector(dateAction:) forControlEvents:UIControlEventValueChanged];
}
}
}
/*! Determines if the UITableViewController has a UIDatePicker in any of its cells.
*/
- (BOOL)hasInlineDatePicker
{
return (self.datePickerIndexPath != nil);
}
/*! Determines if the given indexPath points to a cell that contains the UIDatePicker.
#param indexPath The indexPath to check if it represents a cell with the UIDatePicker.
*/
- (BOOL)indexPathHasPicker:(NSIndexPath *)indexPath
{
return ([self hasInlineDatePicker] && self.datePickerIndexPath.row == indexPath.row);
}
/*! Determines if the given indexPath points to a cell that contains the start/end dates.
#param indexPath The indexPath to check if it represents start/end date cell.
*/
- (BOOL)indexPathHasDate:(NSIndexPath *)indexPath
{
BOOL hasDate = NO;
if ((indexPath.row == kDateStartRow) ||
(indexPath.row == kDateEndRow || ([self hasInlineDatePicker] && (indexPath.row == kDateEndRow + 1))))
{
hasDate = YES;
}
return hasDate;
}
#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
CGFloat height = ([self indexPathHasPicker:indexPath] ? self.pickerCellRowHeight : self.tableView.rowHeight);
return height;
}
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
//{
// return 1;
//}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([self hasInlineDatePicker])
{
// we have a date picker, so allow for it in the number of rows in this section
NSInteger numRows = self.dataArray.count;
return ++numRows;
}
return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = nil;
NSString *cellID = kDateCellID;
if ([self indexPathHasPicker:indexPath])
{
// the indexPath is the one containing the inline date picker
cellID = kDatePickerID; // the current/opened date picker cell
}
else if ([self indexPathHasDate:indexPath])
{
// the indexPath is one that contains the date information
cellID = kDateCellID; // the start/end date cells
}
cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (!cell) {
cell = [self createCellWithIdetifier:cellID];
}
if (indexPath.row == 0)
{
// we decide here that first cell in the table is not selectable (it's just an indicator)
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
// if we have a date picker open whose cell is above the cell we want to update,
// then we have one more cell than the model allows
//
NSInteger modelRow = indexPath.row;
if (self.datePickerIndexPath != nil && self.datePickerIndexPath.row < indexPath.row)
{
modelRow--;
}
NSDictionary *itemData = self.dataArray[modelRow];
// proceed to configure our cell
if ([cellID isEqualToString:kDateCellID])
{
// we have either start or end date cells, populate their date field
//
cell.textLabel.text = [self.dataArray objectAtIndex:indexPath.row];
//cell.detailTextLabel.text = [self.dateFormatter stringFromDate:[itemData valueForKey:kDateKey]];
}
// else if ([cellID isEqualToString:kOtherCell])
// {
// // this cell is a non-date cell, just assign it's text label
// //
// //cell.textLabel.text = [itemData valueForKey:kTitleKey];
// cell.textLabel.text = [self.dataArray objectAtIndex:indexPath.row];
// }
return cell;
}
/*! Adds or removes a UIDatePicker cell below the given indexPath.
#param indexPath The indexPath to reveal the UIDatePicker.
*/
- (void)toggleDatePickerForSelectedIndexPath:(NSIndexPath *)indexPath
{
[self.tableView beginUpdates];
NSArray *indexPaths = #[[NSIndexPath indexPathForRow:indexPath.row + 1 inSection:0]];
// check if 'indexPath' has an attached date picker below it
if ([self hasPickerForIndexPath:indexPath])
{
// found a picker below it, so remove it
[self.tableView deleteRowsAtIndexPaths:indexPaths
withRowAnimation:UITableViewRowAnimationFade];
}
else
{
// didn't find a picker below it, so we should insert it
[self.tableView insertRowsAtIndexPaths:indexPaths
withRowAnimation:UITableViewRowAnimationFade];
}
[self.tableView endUpdates];
}
/*! Reveals the date picker inline for the given indexPath, called by "didSelectRowAtIndexPath".
#param indexPath The indexPath to reveal the UIDatePicker.
*/
- (void)displayInlineDatePickerForRowAtIndexPath:(NSIndexPath *)indexPath
{
// display the date picker inline with the table content
[self.tableView beginUpdates];
BOOL before = NO; // indicates if the date picker is below "indexPath", help us determine which row to reveal
if ([self hasInlineDatePicker])
{
before = self.datePickerIndexPath.row < indexPath.row;
}
BOOL sameCellClicked = (self.datePickerIndexPath.row - 1 == indexPath.row);
// remove any date picker cell if it exists
if ([self hasInlineDatePicker])
{
[self.tableView deleteRowsAtIndexPaths:#[[NSIndexPath indexPathForRow:self.datePickerIndexPath.row inSection:0]]
withRowAnimation:UITableViewRowAnimationFade];
self.datePickerIndexPath = nil;
}
if (!sameCellClicked)
{
// hide the old date picker and display the new one
NSInteger rowToReveal = (before ? indexPath.row - 1 : indexPath.row);
NSIndexPath *indexPathToReveal = [NSIndexPath indexPathForRow:rowToReveal inSection:0];
[self toggleDatePickerForSelectedIndexPath:indexPathToReveal];
self.datePickerIndexPath = [NSIndexPath indexPathForRow:indexPathToReveal.row + 1 inSection:0];
}
// always deselect the row containing the start or end date
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
[self.tableView endUpdates];
// inform our date picker of the current date to match the current cell
[self updateDatePicker];
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
respectiveOptions = [[NSArray alloc]init];
respectiveOptions = [ASOR objectAtIndex:indexPath.row];
if ([kDateCellID isEqualToString:cell.reuseIdentifier])
{
[self displayInlineDatePickerForRowAtIndexPath:indexPath];
}
else
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
}
- (UIPickerView*)pickerViewForCell:(UITableViewCell*)cell {
UIPickerView * picker = [[UIPickerView alloc] initWithFrame:cell.bounds];
[picker setDelegate:self];
[picker setDataSource:self];
picker.hidden = YES;
[cell addSubview:picker];
return picker;
}
#pragma mark - Actions
/*! User chose to change the date by changing the values inside the UIDatePicker.
#param sender The sender for this action: UIDatePicker.
*/
//- (void)dateAction:(id)sender
//{
// NSIndexPath *targetedCellIndexPath = nil;
//
// if ([self hasInlineDatePicker])
// {
// // inline date picker: update the cell's date "above" the date picker cell
// //
// targetedCellIndexPath = [NSIndexPath indexPathForRow:self.datePickerIndexPath.row - 1 inSection:0];
// }
// else
// {
// // external date picker: update the current "selected" cell's date
// targetedCellIndexPath = [self.tableView indexPathForSelectedRow];
// }
//
// UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:targetedCellIndexPath];
// UIDatePicker *targetedDatePicker = sender;
//
// // update our data model
// NSMutableDictionary *itemData = self.dataArray[targetedCellIndexPath.row];
// [itemData setValue:targetedDatePicker.date forKey:kDateKey];
//
// // update the cell's date string
// cell.detailTextLabel.text = [self.dateFormatter stringFromDate:targetedDatePicker.date];
//}
// Number of components.
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 1;
}
// Total rows in our component.
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
return [respectiveOptions count];
}
// Display each row's data.
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
return [respectiveOptions objectAtIndex:row];
}
// Do something with the selected row.
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
}
Here is an example of UITableView making use of UIPickerView embedded in the cells.
I am not changing the color of the picker view, cells, height of cells - I will leave that up to you to do something that suits your needs.
But the main idea here is to show you how you could have picker view in cells and be able to get value accordingly.
#interface YourController ()
#property (strong, nonatomic) NSMutableArray *pickerViewsArray;
#end
#implementation YourController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self)
{
// Custom initialization
}
return self;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.pickerViewsArray = [[NSMutableArray alloc] init];
[self createYourPickerViews];
}
- (void)createYourPickerViews
{
for(int x = 0; x < 10; x++) //number of picker views
{
UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:(CGRect){{0, 0}, 150, 10}];
pickerView.delegate = self;
pickerView.dataSource = self;
pickerView.tag = x;
[self.pickerViewsArray addObject:pickerView];
}
}
#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.pickerViewsArray count]; //As mentioned before, this is important.
}
- (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];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
// Configure the cell...
cell.textLabel.text = [NSString stringWithFormat:#"%i", indexPath.row];
[cell.contentView addSubview:(UIPickerView*)[self.pickerViewsArray objectAtIndex:indexPath.row]];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 150.0f; //just some arbitrary value, change it to suit your needs.
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
//tag corresponds to row on tables view.
NSLog(#"view tag:%ld", (long)pickerView.tag);
//row here corresponds to the value selected from picker view.
NSLog(#"view value:%ld", (long)row);
}
- (NSString*) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [NSString stringWithFormat:#"%d", row+1];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
//change this value to suit your needs.
return 10;
}
#end
Finally make sure to do this in your .h:
#interface YourController : UITableViewController <UITableViewDataSource, UITableViewDelegate, UIPickerViewDelegate, UIPickerViewDataSource>
With this you could be able to retrieve the value from picker view from each different cell accordingly.
For UI I leave that to you. Code is tested. Hope this helps.
Post-Comment (Update 2):
I ran it again and I see what you meant, although it didn't happen to me yesterday.
I made changes to the following and ran another test, this will fix it:
In cellForRowAtIndexPath:
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.text = [NSString stringWithFormat:#"%i", indexPath.row];
[cell.contentView addSubview:[self.pickerViewsArray objectAtIndex:indexPath.row]];
}
Another Update (concerning UI: how to hide and un-hide picker when tapped on cells):
Modify this to:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UIPickerView *temp;
temp = [self.pickerViewsArray objectAtIndex:indexPath.row];
if(!temp.isUserInteractionEnabled)
{
[UIView animateWithDuration:1.0f animations:^
{
temp.userInteractionEnabled = YES;
temp.layer.opacity = 1.0f;
}
completion:^(BOOL finished)
{
}];
}
else
{
[UIView animateWithDuration:1.0f animations:^
{
temp.userInteractionEnabled = NO;
temp.layer.opacity = 0.0f;
}
completion:^(BOOL finished)
{
}];
}
}
And in:
- (void)createYourPickerViews
{
for(int x = 0; x < 10; x++)
{
UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:(CGRect){{0, 0}, 150, 10}];
pickerView.delegate = self;
pickerView.dataSource = self;
pickerView.layer.opacity = 0.0f; ======>>> //Add this
pickerView.userInteractionEnabled = NO; =======>>> //And this
pickerView.tag = x;
[self.pickerViewsArray addObject:pickerView];
}
}
Again, code is tested. Hope this (finally) helps.
Related
I have a table view with 5 sections and I have set the tableview selection to multiple. Each section have different number of rows. What I want is to set that the user can select only one cell from each section(in my table user can select any number of cells).
ex: 5 cells from 5 sections.
It should be impossible to select more than one cell from any section. If user select another cell from same section, previously selected cell should be deselected. How can I do this. This is a sample implementation of didSelectRowAtIndexPath.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
HoteldetalcelloneTableViewCell *cellone = (HoteldetalcelloneTableViewCell *)[self.detailtableView cellForRowAtIndexPath:indexPath];
HoteldetailcelltwoTableViewCell *celltwo = (HoteldetailcelltwoTableViewCell *)[self.detailtableView cellForRowAtIndexPath:indexPath];
//I have implement for two sections to test.
if(indexPath.section == 0)
{
HotelDetailsone *secone = [roomonearray objectAtIndex:indexPath.row];
HoteldetailsforBooking *book = [HoteldetailsforBooking new];
if([secone.offerallow isEqualToString:#"True"])
{
celltwo.selectedsignLabel.hidden = NO;
}
else
{
cellone.selectedsignLabelone.hidden = NO;
}
// [self.detailtableView reloadData];
NSLog(#"price for room 1 : %#", secone.itempriceText);
}
else
{
HotelDetailsone *sectwo = [roomtwoarray objectAtIndex:indexPath.row];
HoteldetailsforBooking *book = [HoteldetailsforBooking new];
if([sectwo.offerallow isEqualToString:#"True"])
{
celltwo.selectedsignLabel.hidden = NO;
}
else
{
cellone.selectedsignLabelone.hidden = NO;
}
// [self.detailtableView reloadData];
NSLog(#"price for room 1 : %#", sectwo.itempriceText);
}
}
You need to keep track on the selection of cell. So you need to store selected indexpath in array.
in ViewController.h declare property like this
#property(nonatomic,strong) NSMutableDictionary *selectionData;
Now in ViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
self.selectionData=[[NSMutableDictionary alloc]init];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
TestTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"mycell"];
if ([self.selectionData objectForKey:[NSString stringWithFormat:#"%ld",(long)indexPath.section] ] != nil) {
NSMutableArray *sectionData=[[self.selectionData objectForKey:[NSString stringWithFormat:#"%ld",(long)indexPath.section]] mutableCopy];
if (![sectionData containsObject:[NSNumber numberWithLong:indexPath.row]])
{
cell.accessoryType = UITableViewCellAccessoryNone;
cell.numberlabel.text = #"2";
}
else
{
cell.numberlabel.text = #"***";
cell.accessoryType=UITableViewCellAccessoryCheckmark;
}
}
else
{
cell.numberlabel.text = #"2";
cell.accessoryType = UITableViewCellAccessoryNone;
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"selected section :%li ---> selected row :%li",(long)indexPath.section, (long)indexPath.row);
[self handleSelectionForSection:indexPath.section row:indexPath.row];
[self.tablev reloadData];
}
-(void)handleSelectionForSection:(long)sectionIndex row:(long)rowIndex
{
if ([self.selectionData objectForKey:[NSString stringWithFormat:#"%ld",sectionIndex] ] != nil) {
NSMutableArray *sectionData=[[self.selectionData objectForKey:[NSString stringWithFormat:#"%ld",sectionIndex]] mutableCopy];
if (![sectionData containsObject:[NSNumber numberWithLong:rowIndex]])
{
//removing previous selected rows
[sectionData removeAllObjects];
[sectionData addObject:[NSNumber numberWithLong:rowIndex]];
[self.selectionData setObject:sectionData forKey:[NSString stringWithFormat:#"%ld",sectionIndex]];
}
else
{
//cell you tapped is already selected,
// you can deselect it by removing object
//if you dont want to deselect it comment following lines
[sectionData removeObject:[NSNumber numberWithLong:rowIndex]];
[self.selectionData setObject:sectionData forKey:[NSString stringWithFormat:#"%ld",sectionIndex]];
}
}
else
{
//section key not available so we need to create it
NSMutableArray *sectionData=[[NSMutableArray alloc]init];
[sectionData addObject:[NSNumber numberWithLong:rowIndex]];
[self.selectionData setObject:sectionData forKey:[NSString stringWithFormat:#"%ld",sectionIndex]];
}
NSLog(#"All Selection : %#",self.selectionData);
}
Your numberOfRowsInSection, numberOfSectionsInTableView and titleForHeaderInSection will remain same.
Let me know if you have any query.
You can set selection property of tableview from interface builder. Select your tableview in IB and then select attribute inspector and setsingle selectiontoselection` property like below screenshot.
Or you can set programattically,
self.tableView.allowsMultipleSelection = NO;
Update :
If you want single selection per section then you can implement willSelectRowAtIndexPath as below,
- (NSIndexPath*)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath*)indexPath {
for ( NSIndexPath* selectedIndexPath in tableView.indexPathsForSelectedRows ) {
if ( selectedIndexPath.section == indexPath.section )
[tableView deselectRowAtIndexPath:selectedIndexPath animated:NO] ;
}
return indexPath ;
}
In this case you should allow multiple selection in tableview i think.
Reference : Answer of John Sauer
Looks like you are updating celltwo / cellone selectedsignLabel.hidden on table selection. so #Lion solution will not working. You have to save the last selected index using below code :
#property (nonatomic, strong) NSMutableDictionary *selectedIndexPathDict;
// in viewDidLoad:
self.tableView.allowsMultipleSelection = YES;
self.selectedIndexPathDict = [[NSMutableDictionary alloc] init];
//In table view delegate.
- (NSIndexPath*)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath*)indexPath {
NSString *indexSection = [NSString stringWithFormat:#"%ld", (long)indexPath.section];
NSIndexPath *indexPath1 = self.selectedIndexPathDict[indexSection];
if ( indexPath1) {
HotelDetailsone *secone = [roomonearray objectAtIndex:indexPath.row];
secone.offerallow ^= YES; //toggle bool value
// update new selected index path.
[self.selectedIndexPathDict setObject:indexPath forKey:indexSection];
//reload previous selected cell.
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(),^{
[tableView beginUpdates];
[tableView reloadRowsAtIndexPaths:#[indexPath1] withRowAnimation:UITableViewRowAnimationFade];
[tableView endUpdates];
});
} else {
//initialise selected index path
self.selectedIndexPathDict[indexSection] = indexPath;
}
[tableView deselectRowAtIndexPath:indexPath animated:NO] ;
return indexPath ;
}
I have not update the complete working code. But this is the way to achieve. You can also use the userdefault instead of self.selectedIndexPathDict.
First of all: I know that some people already posted topics like that, but nobody gave a clear answer in all those topics.
I have a settings-UITableView in my application. Now i want to add a TableViewCell where i can choose between some numbers with a UIPickerView.
In the tableView didSelectRowAtIndexPath method i created the if statement for the right cell
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.row == 1){
}
}
How can i add a UIPickerView for this cell? It should slide up from the bottom and it would be nice if there is something like a "done" button.
Have you seen the sample program released with iOS 7 called DateCell? It uses a UIDatePicker, but I found it pretty straightforward to adapt it to a regular UIPickerView.
It does exactly what you're describing: edit a UITableViewCell with a picker that opens directly under the row you're editing.
This is also based on your other question, so I am including those functionalities here as well (i.e. the switch).
In your YourTableViewController.h
set:
#interface YourTableViewViewController : UITableViewController <UIPickerViewDataSource, UIPickerViewDelegate>
In your YourTableViewController.m
Paste this code:
#interface YourTableViewViewController ()
#property NSInteger toggle;
#property (strong, nonatomic) UIPickerView *pickerView;
#end
#implementation YourTableViewViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.toggle = 0;
self.pickerView = [[UIPickerView alloc] initWithFrame:(CGRect){{0, 0}, 320, 480}];
self.pickerView.delegate = self;
self.pickerView.dataSource = self;
self.pickerView.center = (CGPoint){160, 640};
self.pickerView.hidden = YES;
[self.view addSubview:self.pickerView];
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return 2;
}
- (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];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
if(indexPath.row == 0)
{
[cell.contentView addSubview:self.mySwitch];
}
if(indexPath.row == 1)
{
cell.textLabel.textColor = [UIColor darkGrayColor];
if(self.toggle == 0)
{
cell.textLabel.text = #"Choose a number";
}
else
{
cell.textLabel.text = #"Cancel";
}
}
// Configure the cell...
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.row == 1)
{
if(self.toggle == 0)
{
self.toggle = 1;
[self.tableView reloadRowsAtIndexPaths:#[indexPath] withRowAnimation:YES];
[self bringUpPickerViewWithRow:indexPath];
}
else
{
self.toggle = 0;
[self.tableView reloadRowsAtIndexPaths:#[indexPath] withRowAnimation:YES];
[self hidePickerView];
}
}
}
- (void)bringUpPickerViewWithRow:(NSIndexPath*)indexPath
{
UITableViewCell *currentCellSelected = [self.tableView cellForRowAtIndexPath:indexPath];
[UIView animateWithDuration:1.0f
delay:0.0f
options:UIViewAnimationOptionCurveEaseInOut
animations:^
{
self.pickerView.hidden = NO;
self.pickerView.center = (CGPoint){currentCellSelected.frame.size.width/2, self.tableView.frame.origin.y + currentCellSelected.frame.size.height*4};
}
completion:nil];
}
- (void)hidePickerView
{
[UIView animateWithDuration:1.0f
delay:0.0f
options:UIViewAnimationOptionCurveEaseInOut
animations:^
{
self.pickerView.center = (CGPoint){160, 800};
}
completion:^(BOOL finished)
{
self.pickerView.hidden = YES;
}];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
self.toggle = 0;
[self.tableView reloadData];
[self hidePickerView];
NSLog(#"row selected:%ld", (long)row);
}
- (NSString*) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [NSString stringWithFormat:#"%d", row+1];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return 10;
}
#end
Tested.
Addendum:
Also, in your storyboard, change the separator for YourTableView to None (looks better in your case here).
Table View Separator:
in viewDidLoad, add:
self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
And in bringUpPickerViewWithRow
after:
UITableViewCell *currentCellSelected = [self.tableView cellForRowAtIndexPath:indexPath];
add:
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
[self.tableView setNeedsDisplay];
And lastly, in hidePickerView, add:
self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
[self.tableView setNeedsDisplay];
Create custom ViewController that include UIPickerView and Done
button.
Add it as subview on your tableview. (Place it bottom so
that it does not visible).
Once user click appropriate cell, you
can animate picker-view from bottom.
Once user select an item
animate and position it to bottom.
I have done above steps for same purpose. If you want I can send custom controller that include UIPickerView and done button.
So basically I am getting the wrong data on every textField by scrolling my TableView (Everything is mixed up). I know, this is because the awesome optimization of the reusable cells in the UITableView, so the indexpath are changing constantly, but still I don't know how to solve this.
Having an UILabel in the same cell I solved this problem by adding a specific tag in every label view, so the tableview knows which data is going to return on a view but for some reason this is not possible for my textfield view.
Here is my code:
#define DESCRIPTION_TAG 10
#define TEXTFIELD_TAG 11
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Description Cell";
// Intatiating my own TableViewCell
CustomLocationCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (!cell){
cell = [[CustomLocationCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.rowText = (UILabel *) [cell viewWithTag:DESCRIPTION_TAG]; // returning view with unique tag
cell.rowTextField = (UITextField *)[cell viewWithTag:TEXTFIELD_TAG]; // NOT WORKING!!! Data get mix up
cell.rowTextField.delegate = cell; // sending the delegate to custom class cell
cell.delegate = self; // make connection with my #protocol
switch (indexPath.section) {
case 0:
cell.rowText.text = [self.descriptions objectAtIndex:indexPath.row];
cell.rowTextField.placeholder = [self.descriptionsPlaceholder objectAtIndex:indexPath.row];
break;
case 1:
cell.rowText.text = [self.rooms objectAtIndex:indexPath.row];
cell.rowTextField.placeholder = [self.contentPlaceholder objectAtIndex:indexPath.row];
break;
default:
break;
}
return cell;
}
Any help is appreciated.
Here is an update of my data source:
On my CustomTableViewCell I do have outlets for my UILabel and UITextfield
// UITableView DataSource
- (NSArray *)sections
{
if (!_sections){
_sections = [[NSArray alloc] initWithObjects:#"First Description", #"Second Descriptions", nil];
}
return _sections;
}
- (NSMutableArray *)rooms
{
if (!_rooms){
_rooms = [[NSMutableArray alloc] init];
}
return _rooms;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return self.sections.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
switch (section) {
case 0:
return [self.descriptions count];
break;
case 1:
return [self.rooms count];
break;
default:
break;
}
return 0;
}
I'm not sure exactly what you're trying to accomplish, but here's an example that works with labels and text fields with placeholder text. You'll notice that in cellForRowAtIndexPath, I set both the text and placeholder to nil, so that when a cell is reused, it doesn't have the wrong text in it. Also, when doing the text fields, I check if the array has placeholder text at that index, and if so, I reset the placeholder, and if not I reset the text.
In order for the text field delegate methods to work properly, each text filed needs a unique tag (not just one tag for labels and another for text fields) that I set equal to (indexPath.row + 1000*indexPath.section).
#import "TableController.h"
#import "CustomLocationCell.h"
#interface TableController ()
#property (strong,nonatomic) NSArray *descriptions;
#property (strong,nonatomic) NSMutableArray *descriptionsPlaceholder;
#property (strong,nonatomic) NSArray *rooms;
#property (strong,nonatomic) NSMutableArray *contentPlaceholder;
#end
#implementation TableController
- (void)viewDidLoad {
[super viewDidLoad];
self.descriptions = #[#"One",#"Two",#"Three",#"Four",#"Five",#"Six",#"Seven",#"Eight"];
self.descriptionsPlaceholder = [#[#"Placeholder1",#"Placeholder2",#"Placeholder3",#"Placeholder4",#"Placeholder5",#"Placeholder6",#"Placeholder7",#"Placeholder8"] mutableCopy];
self.rooms = #[#"Room1", #"Room2", #"Room3", #"Room4",#"Room5", #"Room6", #"Room7", #"Room8"];
self.contentPlaceholder = [#[#"ContentPH1",#"ContentPH2",#"ContentPH3",#"ContentPH4",#"ContentPH5",#"ContentPH6",#"ContentPH7",#"ContentPH8"] mutableCopy];
[self.tableView reloadData];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.descriptions.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Description Cell";
CustomLocationCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.rowTextField.delegate = self;
cell.rowTextField.tag = indexPath.row + 1000*indexPath.section;
cell.rowTextField.placeholder = nil;
cell.rowTextField.text = nil;
switch (indexPath.section) {
case 0:
cell.rowText.text = [self.descriptions objectAtIndex:indexPath.row];
if ([self.descriptionsPlaceholder[indexPath.row] hasPrefix:#"Placeholder"]) {
cell.rowTextField.placeholder = [self.descriptionsPlaceholder objectAtIndex:indexPath.row];
}else{
cell.rowTextField.text = [self.descriptionsPlaceholder objectAtIndex:indexPath.row];
}
break;
case 1:
cell.rowText.text = [self.rooms objectAtIndex:indexPath.row];
if ([self.contentPlaceholder[indexPath.row] hasPrefix:#"ContentPH"]) {
cell.rowTextField.placeholder = [self.contentPlaceholder objectAtIndex:indexPath.row];
}else{
cell.rowTextField.text = [self.contentPlaceholder objectAtIndex:indexPath.row];
}
break;
default:
break;
}
return cell;
}
-(void)textFieldDidEndEditing:(UITextField *)textField {
if (textField.tag >= 1000 && ![textField.text isEqualToString: #""]) {
[self.contentPlaceholder replaceObjectAtIndex:textField.tag - 1000 withObject:textField.text];
}else if (textField.tag < 1000 && ![textField.text isEqualToString: #""]) {
[self.descriptionsPlaceholder replaceObjectAtIndex:textField.tag withObject:textField.text];
}
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
I'm developing an iOS application with latest SDK.
I have a UITableView with a custom UITableViewCell:
#interface FavouriteCell : UITableViewCell
#property (unsafe_unretained, nonatomic) IBOutlet UIImageView *selectIcon;
#property (unsafe_unretained, nonatomic) IBOutlet UILabel *favName;
#property (nonatomic) BOOL checked;
+ (NSString *)reuseIdentifier;
#end
On selectIcon I set two images from normal and highlighted. When I do cell.checked = !selected; on tableView:didSelectRowAtIndexPath: it works perfectly.
But when I try to reset every selected cell on clearSelectedFavourites:, it doesn't work.
#interface FavViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate, UIAlertViewDelegate>
{
#private
NSMutableArray* _favsSelected;
BOOL* _isOnEditingMode;
}
// ######### FavViewController implementation ##############
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
self.title = NSLocalizedString(#"Favoritos", #"Favoritos");
self.tabBarItem.image = [UIImage imageNamed:#"fav"];
_favsSelected = [[NSMutableArray alloc] init];
_isOnEditingMode = NO;
}
return self;
}
- (UITableViewCell* )tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"cellForRowAtIndexPath");
static NSString* CellIdentifier = #"FavCell";
FavouriteCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
[[NSBundle mainBundle] loadNibNamed:#"FavouriteCell" owner:self options:nil];
cell = _favCell;
self.favCell = nil;
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.favName.font = [UIFont systemFontOfSize:15.0f];
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
#pragma mark - UITableViewDelegate methods
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"didSelectRowAtIndexPath: %#", indexPath);
if (tableView.isEditing)
{
BOOL selected = NO;
if ((_favsSelected != nil) && ([_favsSelected count] > 0))
selected = ([_favsSelected indexOfObject:indexPath] != NSNotFound);
FavouriteCell* cell =
(FavouriteCell*)[tableView cellForRowAtIndexPath:indexPath];
NSLog(cell.checked ? #"Yes" : #"No");
cell.checked = !selected;
if (selected)
[_favsSelected removeObject:indexPath];
else
[_favsSelected addObject:indexPath];
}
}
- (IBAction)editFavList:(id)sender
{
NSLog(#"edit button clicked!");
if ([_favList isEditing])
{
[self clearSelectedFavourites];
[_favList setEditing:NO animated:YES];
[_editButton setImage:[UIImage imageNamed:#"ButtonEdit.png"] forState:UIControlStateNormal];
}
else
{
[_favList setEditing:YES animated:YES];
[_editButton setImage:[UIImage imageNamed:#"done_button.png"] forState:UIControlStateNormal];
}
}
- (void)clearSelectedFavourites
{
for(int index = 0; index < [_favsSelected count]; index++)
{
NSIndexPath* indexPath = (NSIndexPath*)[_favsSelected objectAtIndex:index];
FavouriteCell* cell = (FavouriteCell*)[self tableView:_favList cellForRowAtIndexPath:indexPath];
cell.checked = NO;
}
[_favsSelected removeAllObjects];
}
- (void)configureCell:(FavouriteCell *)cell
atIndexPath:(NSIndexPath *)indexPath
{
NSManagedObject *object = nil;
object = [self.favListFetchedResultsController objectAtIndexPath:indexPath];
cell.favName.text = [[object valueForKey:#"name"] description];
}
Do you know why?
I have tried to set selectIcon to not hightlighted manually, but it doesn't work, and that code if the latest test I did.
I have also tested this: [cell setHighlighted:NO]; on clearSelectedFavourites: and it doesn't work.
You are not showing us your custom [self configureCell:cell atIndexPath:indexPath]; function, so I cannot know what's going on.
However a few things first:
The cells on the TableView are being reused.
So you cell select state needs to be set every time for each cell.
Also on your clearSelectedFavourites function, you are getting a reference to all selected cells, then clear their selection, which is pointless, because the cells are going to be reused.
You only need to loop through the visible UITableView cells and change their selection status, then clear your _favsSelected array...
- (void)clearSelectedFavourites
{
NSArray *cells = [self.tableView visibleCells];
for (FavouriteCell *cell in cells)
{
cell.checked = NO;
//might not be needed, or might be needed
[cell setNeedsDisplay];
}
[_favsSelected removeAllObjects];
}
Finally on your configureCell function, you should check if the cell should be checked or not, based on your _favsSelected array entries and just select it or not.
Edit
In your configureCell function you should check if the cell needs to be checked or not:
- (void)configureCell:(FavouriteCell *)cell
atIndexPath:(NSIndexPath *)indexPath
{
NSManagedObject *object = nil;
object = [self.favListFetchedResultsController objectAtIndexPath:indexPath];
cell.favName.text = [[object valueForKey:#"name"] description];
cell.checked = [_favsSelected containsObject:indexPath];
}
You can do like this :
[tbl beginUpdates];
/* call you method with animation */
[tbl endUpdates];
[tbl reloadData];
my tableview changes values when I scroll up or down. It seems to use the same values from other parts of the table. I imagine its an error in my cell creation, here is the code.
Please tell me what I did wrong, thank you!
EDITED ADDED WHOLE CODE
//global indexpath to remember which cell tapped
NSIndexPath *globalPath;
#interface SearchViewController ()
#end
#implementation SearchViewController
//Load implementation once per launch
- (void)viewDidLoad
{
[super viewDidLoad];
[self linkInputTableToDelegate];
_temporaryResultsArray =[[NSMutableArray alloc]init];
_flurryArray=[[NSMutableArray alloc]init];
_numberOfSections=6;
}
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:NO];
[InputTable reloadData];
textFromUserDefaults=[[[HelperMethods alloc]init]getObjectUserDefault:#"textFiltered"];
[self addTextToFlurryArrayForFlurryAndSavedLists:_textFromUserDefaults];
}
-(void)viewDidDisappear:(BOOL)animated{
}
- (IBAction)searchButtonPressed:(UIButton *)sender {
self.tabBarController.selectedIndex = 1;
}
//Makes the input table respond to delegate table view methods
-(void)linkInputTableToDelegate{
_inputTable.dataSource=self;
_inputTable.delegate=self;
}
-(void)performSearch:(NSString*)text{
//do search
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
int numberOfRows=_numberOfSections;
//Rows for iPhone 4
if ([[UIScreen mainScreen]bounds].size.height==480) {
numberOfRows=numberOfRows;
//Rows for iPhone 5
}else if ([[UIScreen mainScreen]bounds].size.height==568){
numberOfRows=numberOfRows+1;
}
return numberOfRows;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//In reality groups are created with 1 row inside, this is to allow spacing between the rows
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *kCellID = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellID];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellID];
}
//Is the cell the same as the one clicked when going to ingredient filter
BOOL cellIndexPathSameAsSelected=[self isCellIndexSameAsPreviousClicked:indexPath];
cell.textLabel.textColor=[UIColor blackColor];
if (cellIndexPathSameAsSelected && _textFromUserDefaults!=nil) {
if (![cell.textLabel.text isEqualToString:_textFromUserDefaults]) {
cell.textLabel.text=_textFromUserDefaults;
[self performTextSearch:_textFromUserDefaults];
}
}
return cell;
}
//Compares the previous clicked cell with the cell now selected
-(BOOL)isCellIndexSameAsPreviousClicked: (NSIndexPath*)cellPath{
if (cellPath.row == globalPath.row && globalPath.section==cellPath.section) {
return YES;
}
else{
return NO;
}
}
- (void)updateTableViewWithExtraRow :(NSIndexPath*)rowSelected{
NSLog(#"number of sections =%i",_numberOfSections);
if (rowSelected.section == _numberOfSections) {
_numberOfSections ++;
}
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellText = [tableView cellForRowAtIndexPath:indexPath].textLabel.text;
[[[HelperMethods alloc]init]saveObjectToUserDefaults:cellText :#"textFiltered"];
globalPath = indexPath;
[self updateTableViewWithExtraRow:indexPath];
}
-(void)addTextToFlurryArrayForFlurryAndSavedLists:(NSString*)text{
if ([_flurryArray count]==0 &&[text length]>0) {
[_flurryArray addObject:text];
}
for (int i=0;i<[_flurryArray count];i++) {
NSString *textInArray=[_flurryArray objectAtIndex:i];
if (![textInArray isEqualToString:text]) {
[_flurryArray addObject:text];
}
}
NSLog(#"Total number of saved items = %i",[_flurryArray count]);
}
// Dispose of any resources that can be recreated.
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
The problem is you are only changing the texts in the cells, when those conditions are met. For example, when your cellIndexPathSameAsSelected is NO, you leave the cell unmodified. So you should add an else and do some settings there too.
EDIT:
if (cellIndexPathSameAsSelected && _textFromUserDefaults!=nil) {
if (![cell.textLabel.text isEqualToString:_textFromUserDefaults]) {
cell.textLabel.text=_textFromUserDefaults;
[self performTextSearch:_textFromUserDefaults];
}
} else {
cell.textLabel.text = [NSString string];
}
After your [tableView dequeueReusableCellWithIdentifier:kCellID]; call, you have to check if your cell can actually be reusable or not with the followings statements :
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:...];
}
You should be doing something like this
static NSString *kCellID = #"Cell";
// Acquire the cell if possible.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellID];
if (cell == nil) // Not possible to re-use cell, so create a new cell
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellID];
}