At one point of time, only one section would be opened [closed] - ios

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
when i click first section getting follwing error:
Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-2903.2/UITableView.m:1076
2014-02-26 14:12:38.935 ExpandableTableCells[1865:a0b]
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to delete row 8 from section 0 which only contains 1 rows before the update'
give me solution...
thanks...
code:
#pragma mark - Expanding
- (BOOL)tableView:(UITableView *)tableView canCollapseSection:(NSInteger)section
{
if (section>=0) return YES;
return NO;
//return YES;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"------->%d",section);
if (section==0)
{
if ([expandedSections containsIndex:section])
{
// return 5; // return rows when expanded
NSLog(#"%d",[self.alpha count]);
return [self.alpha count];
}
return 1;
}
if (section==1) {
if ([expandedSections containsIndex:section])
{
// return 5; // return rows when expanded
NSLog(#"vvv%d",[self.numbers count]);
return [self.numbers count];
}
return 1;
}
if (section==2)
{
if ([expandedSections containsIndex:section])
{
// return 5; // return rows when expanded
NSLog(#"%d",[self.colors count]);
return [self.colors count];
}
return 1;
}
return YES;
}
- (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];
}
// Configure the cell...
if (indexPath.section==0) {
if ([self tableView:tableView canCollapseSection:indexPath.section])
{
if (!indexPath.row)
{
// first row
cell.textLabel.text = #"Alaphabet"; // only top row showing
if ([expandedSections containsIndex:indexPath.section])
{
cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeUp];
}
else
{
cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeDown];
}
}
else
{
// all other rows
cell.textLabel.text = [self.alpha objectAtIndex:indexPath.row];
cell.accessoryView = nil;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
}
}
if (indexPath.section==1) {
if ([self tableView:tableView canCollapseSection:indexPath.section])
{
if (!indexPath.row)
{
// first row
cell.textLabel.text = #"numbers"; // only top row showing
if ([expandedSections containsIndex:indexPath.section])
{
cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeUp];
}
else
{
cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeDown];
}
}
else
{
// all other rows
cell.textLabel.text = [self.numbers objectAtIndex:indexPath.row];
cell.accessoryView = nil;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
}
}
if (indexPath.section==2) {
if ([self tableView:tableView canCollapseSection:indexPath.section])
{
if (!indexPath.row)
{
// first row
cell.textLabel.text = #"colors"; // only top row showing
if ([expandedSections containsIndex:indexPath.section])
{
cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeUp];
}
else
{
cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeDown];
}
}
else
{
// all other rows
cell.textLabel.text = [self.colors objectAtIndex:indexPath.row];
cell.accessoryView = nil;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
}
}
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self tableView:tableView canCollapseSection:indexPath.section])
{
if (!indexPath.row)
{
[self.tableView beginUpdates];
// only first row toggles exapand/collapse
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSInteger section = indexPath.section;
NSLog(#"section------%d",section);
BOOL currentlyExpanded = [expandedSections containsIndex:section];
NSLog(#"current expand------%d",currentlyExpanded);
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];
NSLog(#"rows------%d",rows);
}
for (int i=1; i<rows; i++)
{
NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i inSection:section];
[tmpArray addObject:tmpIndexPath];
NSLog(#"temp array----->%#",tmpArray);
}
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (currentlyExpanded)
{
[tableView deleteRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeDown];
}
else
{
[tableView insertRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
NSLog(#"open index------%d",openSectionIndex);
if (openSectionIndex != -1)
{
[tmpArray removeAllObjects];
rows = [self tableView:tableView numberOfRowsInSection:openSectionIndex];
[expandedSections removeIndex:openSectionIndex];
for (int i=1; i<rows; i++)
{
NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i
inSection:openSectionIndex];
[tmpArray addObject:tmpIndexPath];
}
[tableView deleteRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
}
openSectionIndex=section;
cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeUp];
}
[self.tableView endUpdates];
}
}
}

#interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
{
int selectedIndex;
UITableView *menuTableView;
NSMutableArray *colorsArray, *numberArray, *alphaArray ;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
selectedIndex=50;
colorsArray =[[NSMutableArray alloc]initWithObjects:#"red",#"yellow",#"pink",#"none", nil];
numberArray =[[NSMutableArray alloc]initWithObjects:#"1",#"2",#"3",#"4",#"5",#"6", nil];
alphaArray =[[NSMutableArray alloc]initWithObjects:#"a",#"b",#"c",#"d",#"e", nil];
menuTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 60, 320, 404) style:UITableViewStyleGrouped];
menuTableView.delegate=self;
menuTableView.dataSource=self;
menuTableView.separatorColor=[UIColor grayColor];
[self.view addSubview:menuTableView];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 3;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int count=0;
if (section ==selectedIndex) {
switch (section) {
case 0:
count= colorsArray.count;
break;
case 1:
count= numberArray.count;
break;
case 2:
count= alphaArray.count;
break;
default:
break;
}
}
else
{
count= 1;
}
return count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 60;
}
-(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];
}
for (UIView *view in cell.contentView.subviews) {
[view removeFromSuperview];
}
switch (indexPath.section) {
case 0:
cell.textLabel.text =colorsArray[indexPath.row];
break;
case 1:
cell.textLabel.text =numberArray[indexPath.row];
break;
case 2:
cell.textLabel.text =alphaArray[indexPath.row];
break;
default:
break;
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 60;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIButton *titleButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
titleButton.frame = CGRectMake(0, 0, 320, 30);
[titleButton setBackgroundColor:[UIColor redColor]];
[titleButton addTarget:self action:#selector(handleTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
titleButton.tag = section;
NSString *sectionName;
switch (section)
{
case 0: sectionName = NSLocalizedString(#"Colors", #"Colors");
break;
case 1: sectionName = NSLocalizedString(#"Numbers", #"Numbers");
break;
case 2: sectionName = NSLocalizedString(#"Alabaphet", #"Alabaphet");
break;
default: sectionName = #"";
break;
}
[titleButton setTitle:sectionName forState:UIControlStateNormal];
return titleButton;
}
-(void)handleTouchUpInside:(UIButton *)sender
{
if(selectedIndex== sender.tag)
{
selectedIndex=50;
}
else
{
selectedIndex= sender.tag;
}
[menuTableView reloadData];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// secondviewcontroller *sec =[[secondviewcontroller alloc]init];
switch (indexPath.section) {
case 0:
NSLog(#"%#",colorsArray[indexPath.row]);
//sec.arrayobjectInsecondClass =colorsArray[indexPath.row];
break;
case 1:
NSLog(#"%#",numberArray[indexPath.row]);
//sec.arrayobjectInsecondClass =numberArray[indexPath.row];
break;
case 2:
NSLog(#"%#",alphaArray[indexPath.row]);
//sec.arrayobjectInsecondClass =alphaArray[indexPath.row];
break;
default:
break;
}
// [self.navigationController pushViewController:sec animated:NO];
}

Related

Checkmark multiple rows by loading NSUserDefaults

I'm asking the user to select options in a UITableView and then saving the selection in NSUserDefaults. I'm making sure that if the user selects an option twice, it gets added only once..i.e no duplicates.
I'm loading the NSUserDefaults and then trying to show the rows as "checked"..so that the user remembers what he/she had selected when they had run the app earlier.
Now, I know that only the cellForRowAtIndexPath method can set a checkmark.
The below code only checkmarks the last object. But how do I get multiple checkmarks?
This is how far I've gotten.
- (void)viewDidLoad {
[super viewDidLoad];
appSettings = [NSUserDefaults standardUserDefaults];
self.title = #"Select News Categories";
_selectedCategoriesArray = [[NSMutableArray alloc] init];
[self initNewsCategories];
[self loadNewsSelectedCategories];
}
#pragma mark UITableViewDataSource methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_newsCategoriesArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cellNewsCategory" forIndexPath:indexPath];
// Configure the cell...
cell.textLabel.text = [NSString stringWithFormat:#"%#",[_newsCategoriesArray objectAtIndex:indexPath.row]];
NSString * cellText = [[cell textLabel] text];
for (NSString * lbl in _selectedNewsCategories)
{
if ([cellText isEqualToString:lbl])
{
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
}
else
{
[cell setAccessoryType:UITableViewCellAccessoryNone];
}
}
return cell;
}
#pragma mark UITableViewDelegate methods
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
UITableViewCell * selectedCell = [tableView cellForRowAtIndexPath:indexPath];
NSString * selectedCategory = [[selectedCell textLabel] text];
if ([tableView cellForRowAtIndexPath:indexPath].accessoryType == UITableViewCellAccessoryNone)
{
[[tableView cellForRowAtIndexPath:indexPath] setAccessoryType:UITableViewCellAccessoryCheckmark];
NSLog(#"%#", selectedCategory);
[_selectedCategoriesArray addObject:selectedCategory];
NSLog(#"_selectedCategoriesArray:%#", _selectedCategoriesArray);
[appSettings setObject:_selectedCategoriesArray forKey:#"selectedNewsCategories"];
}
else if ([tableView cellForRowAtIndexPath:indexPath].accessoryType == UITableViewCellAccessoryCheckmark)
{
[[tableView cellForRowAtIndexPath:indexPath] setAccessoryType:UITableViewCellAccessoryNone];
NSLog(#"%#", selectedCategory);
[_selectedCategoriesArray removeObject:selectedCategory];
NSLog(#"_selectedCategoriesArray:%#", _selectedCategoriesArray);
[appSettings setObject:_selectedCategoriesArray forKey:#"selectedNewsCategories"];
}
else
{
[[tableView cellForRowAtIndexPath:indexPath] setAccessoryType:UITableViewCellAccessoryNone];
}
[appSettings synchronize];
}
#pragma mark Helper methods
-(void) initNewsCategories
{
_newsCategoriesArray = [NSArray arrayWithObjects:#"Arts",#"Business",#"Company",
#"Entertainment",#"Environment",#"Health",#"Lifestyle",
#"Media",#"Money",#"Most Read",#"Trending",#"World",nil];
}
-(void) loadNewsSelectedCategories
{
_selectedNewsCategories = [[NSMutableArray alloc] init];
_selectedNewsCategories = [appSettings objectForKey:#"selectedNewsCategories"];
}
You have a problem in this code:
for (NSString * lbl in _selectedNewsCategories)
{
if ([cellText isEqualToString:lbl])
{
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
}
else
{
[cell setAccessoryType:UITableViewCellAccessoryNone];
}
}
You first checkmark cell but then you continue search and unmark cell.
You need to use this:
for (NSString * lbl in _selectedNewsCategories)
{
if ([cellText isEqualToString:lbl])
{
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
break;
}
else
{
[cell setAccessoryType:UITableViewCellAccessoryNone];
}
}
Or this
if([_selectedNewsCategories indexOfObject: cellText] != NSNotFound)
{
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
}else
{
[cell setAccessoryType:UITableViewCellAccessoryNone];
}

Remove Rows From UITableView from Previous Selected Section

Currently I have a UITableView which is expands and collapses with the current code.
- (BOOL)tableView:(UITableView *)tableView canCollapseSection:(NSInteger)section{
if (section>=0) return YES;
return NO;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
NSInteger numberofRows = 0;
numberofRows = nameArray.count;
if (numberofRows != 0){
self.mainTableView.hidden = false;
}
return numberofRows;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if ([self tableView:tableView canCollapseSection:indexPath.section])
{
if (!indexPath.row)
{
// only first row toggles exapand/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 = [ALCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:ALCustomColoredAccessoryTypeDown];
}
else
{
[tableView insertRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
cell.accessoryView = [ALCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:ALCustomColoredAccessoryTypeUp];
}
}
else {
NSLog(#"Selected Section is %ld and subrow is %ld ",(long)indexPath.section ,(long)indexPath.row);
}
}
}
This works really well and upon selection of a UITableViews section the rows are expanded and populated with the correct data and when the same section is selected the rows are removed and appear collapsed.
However what i want to do is somehow automatically collapse the previous selected section and remove the rows within that previous section when the user selects a new indexpath.section.
I have tried storing the selected section index path to an array removing rows based on this value but I think I'm going about it the wrong way as I get assertion failures.
So my question is as follows :-
How can i automatically collapse (remove rows) from a uitableviews section upon selection of another section
Thanks for your help in advance
Thomas
i have faced this issue when i was writting code for my app and i founded this post that had no any single comment or answer...
You can use this code that i was written for me to colapse previous expanded rows of section when i clicked on other section and expand rows of that section, this code working for me try it...
`
- (BOOL)tableView:(UITableView *)tableView canCollapseSection:(NSInteger)section
{
if (section>=0) return YES;
return NO;
}
static NSInteger Value=0;
static NSInteger Value2=0;
static CFIndex indexPre=0;
static NSMutableArray *preArray;
static NSIndexPath *path;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self tableView:tableView canCollapseSection:indexPath.section])
{
if (!indexPath.row)
{
TableViewCell *cell = (TableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
cell.hideButton.hidden=NO;
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSUInteger index=[expandedSections firstIndex];
if ([expandedSections indexGreaterThanIndex:index])
{
NSLog(#"%lu hhhwww", index);
}
NSInteger section = indexPath.section;
static NSInteger rows;
static NSInteger PreRows;
NSLog(#"%lu MY INDEXES1",(unsigned long)[expandedSections count]);
NSMutableArray *tmpArray = [NSMutableArray array];
preArray = [NSMutableArray array];
BOOL currentlyExpanded = [expandedSections containsIndex:section];
if (currentlyExpanded)
{
rows = [self tableView:tableView numberOfRowsInSection:section];
[expandedSections removeIndex:section];
Value=0;
Value2=0;
cell.hideButton.hidden=YES;
}
else
{
if (Value==0)
{
[expandedSections addIndex:section];
rows = [self tableView:tableView numberOfRowsInSection:section];
PreRows = [self tableView:tableView numberOfRowsInSection:section];
indexPre=indexPath.section;
Value=1;
}
else if (Value==1)
{
Value2=1;
NSLog(#"indexPre == %ld %# my indexxxxx", indexPre, expandedSections);
[expandedSections removeIndex:indexPre];
NSLog(#"indexPre == %ld %# my indexxxxx", indexPre, expandedSections);
[self.tableView reloadData];
[expandedSections addIndex:section];
NSLog(#"indexPre == %ld %# my indexxxxx", indexPre, expandedSections);
rows=[self tableView:tableView numberOfRowsInSection:section];
}
}
NSLog(#"%# MY INDEXES",expandedSections);
if (Value2==1)
{
for (int i=1; i<PreRows; i++)
{
NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i
inSection:indexPre];
[preArray addObject:tmpIndexPath];
}
NSLog(#"my arrray %#", preArray);
for (int i=1; i<rows; i++)
{
NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i
inSection:section];
[tmpArray addObject:tmpIndexPath];
}
NSLog(#"my arrray tmparray%#", preArray);
}
else
{
for (int i=1; i<rows; i++)
{
NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i
inSection:section];
[tmpArray addObject:tmpIndexPath];
}
}
if (currentlyExpanded )
{
[tableView deleteRowsAtIndexPaths:tmpArray
withRowAnimation:NO];
cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeDown];
}
else if(Value==1)
{
if (Value2==1)
{
[tableView beginUpdates];
[tableView insertRowsAtIndexPaths:tmpArray
withRowAnimation:NO];
cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeUp];
[tableView endUpdates];
[tableView beginUpdates];
[tableView endUpdates];
indexPre=indexPath.section;
}
else
{
[tableView insertRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeUp];
}
}
}
}
}
`

UISearchDisplayController does not update search results

I have the following search setup in my app:
- (UISearchBar*)searchBar
{
if (!_searchBar) {
_searchBar = [[UISearchBar alloc] init];
_searchBar.delegate = self;
_searchBar.placeholder = kSearchBarPlaceHolder;
}
return _searchBar;
}
- (UISearchDisplayController*)searchBarDisplayContr
{
if (!_searchBarDisplayContr) {
_searchBarDisplayContr = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
_searchBarDisplayContr.delegate = self;
_searchBarDisplayContr.searchResultsDataSource = self.tableView.dataSource;
_searchBarDisplayContr.searchResultsDelegate = self.tableView.delegate;
_searchBarDisplayContr.searchResultsTableView.backgroundColor = [UIColor clearColor];
_searchBarDisplayContr.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
return _searchBarDisplayContr;
}
- (NSMutableArray *)searchResults
{
if (!_searchResults) {
_searchResults = [NSMutableArray arrayWithCapacity:_restaurants.count];
}
return _searchResults;
}
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
[self.searchResults removeAllObjects];
[self.restaurants enumerateObjectsUsingBlock:^(Restaurant *restaurant, NSUInteger idx, BOOL *stop) {
if ([scope isEqualToString:#"All"] || [restaurant.name isEqualToString:scope]) {
NSRange range = [restaurant.name rangeOfString:searchText
options:(NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch)];
if (range.length > 0) {
[self.searchResults addObject:restaurant];
}
}
}];
}
- (BOOL)searchDisplayController:(UISearchDisplayController*)controller shouldReloadTableForSearchString:(NSString*)searchString
{
[self filterContentForSearchText:searchString
scope:#"All"];
dispatch_async(dispatch_get_main_queue(), ^(void) {
for (UIView *v in controller.searchResultsTableView.subviews) {
if ([v isKindOfClass:[UILabel class]]) {
((UILabel *)v).text = kSearchResultsTableViewNoResultsLabel;
((UILabel *)v).font = [UIFont mediumFontOfSize:20.0f];
((UILabel *)v).textColor = [UIColor blackColor];
break;
}
}
});
return YES;
}
- (BOOL)searchDisplayController:(UISearchDisplayController*)controller shouldReloadTableForSearchScope:(NSInteger)searchOption
{
[self filterContentForSearchText:[self.searchBarDisplayContr.searchBar text]
scope:#"All"];
return YES;
}
But for some reason when I search the searchResultsTableView is not updated / cellForRowAtIndexPath is not called. The tableView delegates and DataSource is setup in my storyboard.
Any ideas why this is happening?
UPDATE:
[self.tableView registerClass:[RestaurantsCell class] forCellReuseIdentifier:cellIdentifier];
[self.searchBarDisplayContr.searchResultsTableView registerClass:[RestaurantsCell class] forCellReuseIdentifier:cellIdentifier];
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchBarDisplayContr.searchResultsTableView) {
return [self.searchResults count];
} else {
return [self.restaurants count];
}
return 0;
}
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
RestaurantsCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
Restaurant *restaurant;
if (tableView == self.searchBarDisplayContr.searchResultsTableView) {
if (self.searchResults.count > 0) {
restaurant = self.searchResults[indexPath.row];
}
} else {
if (self.restaurants.count > 0) {
restaurant = self.restaurants[indexPath.row];
}
}
if (restaurant) {
cell.titleLabel.text = restaurant.name;
}
return cell;
}
This is the offending line:
RestaurantsCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
Should be:
RestaurantsCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier];
Explanation:
If the tableView turns out to be your search results table view, then trying to dequeue a cell with an identifier won't work because it doesn't have prototype cells. Therefore, you have to use self.tableView
Also, your code can be cleaned up a lot:
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
return (tableView == self.tableView) ? self.restaurants.count : self.searchResults.count;
}
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
RestaurantsCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier];
Restaurant *restaurant = (tableView == self.tableView) ? self.restaurants[indexPath.row] ? self.searchResults[indexPath.row];
}
cell.titleLabel.text = restaurant.name;
return cell;
}
Edit
Check out this example

moveRowAtIndexPath doesn't get called

My code doesn't enter the moveRowAtIndexPath part. But it enters into canMoveRowAtIndexPath.
When I click minus, "delete" doesn't appear. How can I solve this? Thank you.
ps:I try to make it work for not the tableview with the SearchDisplayController.
In .h file : UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UISearchDisplayDelegate
`/*viewdidload*/`
self.editbtn addTarget:self action:#selector(toggleEditMode:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)toggleEditMode:(id)sender {
if(self.alerjitableview.isEditing){
[self.alerjitableview setEditing:NO animated:YES];
[self.editbtn setTitle:#"Düzenle" forState:UIControlStateNormal];
}else{
[self.alerjitableview setEditing:YES animated:YES];
[self.editbtn setTitle:#"Bitti" forState:UIControlStateNormal];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
if(tableView== self.alerjitableview)
return[hastaninalerjileri count];
else{
if(tableView == self.searchDisplayController.searchResultsTableView)
if (isSearching) {
return [tanilist count];
} else {
return [list count];
}
else
return [favTanilar count];
}
}
- (BOOL)tableView:(UITableView *)tableView
canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- (BOOL)tableView:(UITableView *)tableView
canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- (void) tableView:(UITableView *)tableView
moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath
toIndexPath:(NSIndexPath *)targetIndexPath
{
//if(tableView == self.searchDisplayController.searchResultsTableView)
if(tableView== self.alerjitableview){
NSUInteger sourceIndex = [sourceIndexPath row];
NSUInteger targetIndex = [targetIndexPath row];
if (sourceIndex != targetIndex)
{
[hastaninalerjileri exchangeObjectAtIndex:sourceIndex
withObjectAtIndex:targetIndex];
}
}
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
if(tableView== self.alerjitableview){
[hastaninalerjileri removeObjectAtIndex:[indexPath row]];
// Animate deletion
NSArray *indexPaths = [NSArray arrayWithObject:indexPath];
[self.alerjitableview deleteRowsAtIndexPaths:indexPaths
withRowAnimation:UITableViewRowAnimationFade];
[self.alerjitableview reloadData];
}
else {
if (tableView == self.taniView)
{
[hastanintanilari removeObjectAtIndex:[indexPath row]];
// Animate deletion
NSArray *indexPaths = [NSArray arrayWithObject:indexPath];
[self.taniTableView deleteRowsAtIndexPaths:indexPaths
withRowAnimation:UITableViewRowAnimationFade];
}
}
}
}
- (CGFloat)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 50.0;
}
- (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];
}
TaniModel *taniInfo =[[TaniModel alloc]init];
if (isSearching && [tanilist count]) {
taniInfo = [tanilist objectAtIndex:indexPath.row];
} else {
taniInfo = [list objectAtIndex:indexPath.row];
}
if(tableView == self.alerjitableview){
OrderAlerjiModel *alerjimodel =[hastaninalerjileri objectAtIndex:indexPath.row];
cell.textLabel.text = alerjimodel.Ad;
if((indexPath.row % 2) ==0)
cell.contentView.backgroundColor=[UIColor colorWithRed:241/256.0 green:237/256.0 blue:237/256.0 alpha:1.0];
return cell;
}
else{
if(tableView == self.searchDisplayController.searchResultsTableView){
cell.textLabel.text = taniInfo.Name;
cell.textLabel.tag=[NSString stringWithFormat:#"%d",taniInfo.Id];
if((indexPath.row % 2) ==0)
cell.contentView.backgroundColor=[UIColor colorWithRed:241/256.0 green:237/256.0 blue:237/256.0 alpha:1.0];
NSAttributedString *attributedText =[[NSAttributedString alloc]initWithString:[NSString stringWithFormat:#"%# ",cell.textLabel.text ] attributes:#{NSFontAttributeName: [UIFont systemFontOfSize:14] }];
CGRect rect = [attributedText boundingRectWithSize:(CGSize){242/2, MAXFLOAT}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
CGSize nameSize = rect.size;
if (nameSize.height <=25)
cell.textLabel.numberOfLines=1;
else if(nameSize.height<=50)
cell.textLabel.numberOfLines=2;
else if(nameSize.height<=100)
cell.textLabel.numberOfLines=3;
return cell;
}else{
FavoriTaniModel *d = [favTanilar objectAtIndex:indexPath.row];
cell.textLabel.text =d.TaniName;
cell.tag = [NSString stringWithFormat:#"%d",d.TaniId];
if((indexPath.row % 2) ==0)
cell.contentView.backgroundColor=[UIColor colorWithRed:241/256.0 green:237/256.0 blue:237/256.0 alpha:1.0];
NSAttributedString *attributedText =[[NSAttributedString alloc]initWithString:cell.textLabel.text attributes:#{
NSFontAttributeName: [UIFont systemFontOfSize:14]
}];
CGRect rect = [attributedText boundingRectWithSize:(CGSize){242/2, MAXFLOAT}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
CGSize nameSize = rect.size;
cell.textLabel.frame =CGRectMake(30, 0, 242, nameSize.height);
if (nameSize.height <=25)
cell.textLabel.numberOfLines=1;
else if(nameSize.height<=50)
cell.textLabel.numberOfLines=2;
else if(nameSize.height<=100)
cell.textLabel.numberOfLines=3;
return cell;
}
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(tableView == self.taniTableView){
if(tableView == self.searchDisplayController.searchResultsTableView){
TaniModel *model=[tanilist objectAtIndex:indexPath.row];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:#"0",#"Id",#"0",#"OrderId",[NSString stringWithFormat:#"%d",model.Id],#"TaniId",model.Name,#"Ad",#"1",#"OrderBy", nil];
OrderTaniModel *orderalerji = [[OrderTaniModel alloc]initWithDictionary:dict];
[hastanintanilari addObject:orderalerji];
[self.taniTableView reloadData];
[self.searchDisplayController.searchResultsTableView setHidden:TRUE];
}
}
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath;
Minus appears when return YES in upper method
In method
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath;
you allow move cell from 1 indexPath to another indexPath.
And you ought to be delegate and datasource to this tableView

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