I am fetching contact from device and show in tableview
but first time on contact screen pop show for contact permission, when i click on okey tableview numberofrow called but cellForRowAtIndexPath calling after 5 seconds
I am using this code (this problem only comes first time when new app install)
and i added delegate and datasource in xib and .h file
-(void)getContactsFromAddressBook
{
addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
ABAddressBookRequestAccessWithCompletion(addressBook,
^(bool granted, CFErrorRef error) {
if (granted)
[self loadContacts];
});
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
[self loadContacts];
}
else {
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:Nil message:#"You don't have permission of access contacts for access go to Setting-> Doubls-> Contacts" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
//Load contact
-(void)loadContacts
{
[arr_Contact removeAllObjects];
CFErrorRef *error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex numberOfPeople = ABAddressBookGetPersonCount(addressBook);
//arr_Contact = (__bridge NSMutableArray*)allPeople;
for(int i = 0; i < numberOfPeople; i++) {
ABRecordRef person = CFArrayGetValueAtIndex( allPeople, i );
NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
//NSLog(#"Name:%# %#", firstName, lastName);
ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
NSString *phoneNumber;
for (CFIndex i = 0; i < ABMultiValueGetCount(phoneNumbers); i++) {
phoneNumber = (__bridge_transfer NSString *) ABMultiValueCopyValueAtIndex(phoneNumbers, i);
// NSLog(#"phone:%#", phoneNumber);
}
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
if(firstName == nil)
{
firstName = #"";
}
if(lastName == nil)
{
lastName = #"";
}
if(phoneNumber == nil)
{
continue;
}
[dic setValue:[NSString stringWithFormat:#"%# %#",firstName,lastName] forKey:#"firstName"];
//[dic setValue:lastName forKey:#"lastName"];
[dic setValue:phoneNumber forKey:#"phonesNum"];
[arr_Contact addObject:dic];
}
NSLog(#"arr all contact %#",arr_Contact);
NSSortDescriptor *sorter = [[NSSortDescriptor alloc]
initWithKey:#"firstName"
ascending:YES
selector:#selector(compare:)] ;
NSArray *sortDescriptors = [NSArray arrayWithObject: sorter];
[arr_Contact sortUsingDescriptors:sortDescriptors];
[arr_afterSearch addObjectsFromArray:arr_Contact];
[self createSectionList:arr_Contact];
}
//create section
- (void) createSectionList: (id) wordArray
{
for (int i = 0; i < 27; i++) [arr_searchContact addObject:[[NSMutableArray alloc] init]];
int k=0;
NSLog(#"arr count is %lu",(unsigned long)[arr_Contact count]);
for (k=0; k<[arr_Contact count]; k++) {
NSString *word = [NSString stringWithFormat:#"%#",[[arr_Contact valueForKey:#"firstName"]objectAtIndex:k]];
if ([word length] == 0) continue;
#try {
range1 = [ALPHA rangeOfString:[[word substringToIndex:1] uppercaseString]];
[[arr_searchContact objectAtIndex:range1.location]addObject:[arr_Contact objectAtIndex:k]];
}
#catch (NSException * e) {
[[arr_searchContact objectAtIndex:26]addObject:[arr_Contact objectAtIndex:k]];
NSLog(#"error");
}
#finally {
}
}
[self.tblContact reloadData];
}
//tableview delegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger rows=0;
if (IsSearching==TRUE) {
rows=[arr_afterSearch count];
}
else{
rows=[[arr_searchContact objectAtIndex:section] count];
}
return rows;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 40;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
NSInteger section=0;
if (IsSearching==TRUE) {
section=1;
}
else{
if ([arr_searchContact count]>0) {
section=[ALPHA_ARRAY count];
}
else{
section=0;
}
}
return section;
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
if (IsSearching==TRUE) {
return nil;
}
else{
return ALPHA_ARRAY;
}
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection: (NSInteger)section
{
// create the parent view that will hold header Label
if (IsSearching==TRUE) {
return nil;
}
else{
if([[arr_searchContact objectAtIndex:section] count]==0)
{
return nil;
}
else {
UIView* customView = [[UIView alloc] initWithFrame:CGRectMake(5.0, 0.0, 320.0, 25.0)];
[customView setBackgroundColor:[UIColor colorWithRed:236.0/255.0 green:239.0/255.0 blue:240.0/255.0 alpha:1.0]];
UILabel * headerLabel = [[UILabel alloc] initWithFrame:CGRectZero];
headerLabel.backgroundColor = [UIColor clearColor];
headerLabel.font = [UIFont systemFontOfSize:14];
headerLabel.frame = CGRectMake(10.0, 0.0, 300.0, 24.0);
[headerLabel setText:[NSString stringWithFormat:#"%#",[ALPHA_ARRAY objectAtIndex:section]]];
[headerLabel setTextColor:[UIColor lightGrayColor]];
[customView addSubview:headerLabel];
return customView;
}
}
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
if (IsSearching==TRUE) {
return 0;
}
else{
if([[arr_searchContact objectAtIndex:section] count]==0)
{
return 0;
}
else
{
return 25;
}
}
}
-(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.backgroundColor=[UIColor clearColor];
cell.accessoryType = UITableViewCellAccessoryNone;
UIView *selectionView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 280, 46)];
[selectionView setBackgroundColor:[UIColor colorWithRed:236.0/255.0 green:82.0/255.0 blue:91.0/255.0 alpha:1.0]];
cell.selectedBackgroundView = selectionView;
if ([tableView respondsToSelector:#selector(setSectionIndexColor:)]) {
tableView.sectionIndexBackgroundColor = [UIColor colorWithRed:250.0/255.0 green:250.0/255.0 blue:250.0/255.0 alpha:0.3];
tableView.sectionIndexTrackingBackgroundColor = [UIColor whiteColor];
}
}
NSMutableDictionary *dic = [arr_Contact objectAtIndex:indexPath.row];
//cell.textLabel.text = [dic objectForKey:#"firstName"];
//cell.lastNameLabel.text = [dic objectForKey:#"lastName"];
if (IsSearching==TRUE) {
NSDictionary *dic=[arr_afterSearch objectAtIndex:indexPath.row];
if ([[dic objectForKey:#"firstName"] length]>0) {
cell.textLabel.text = [dic objectForKey:#"firstName"];
}
else{
cell.textLabel.text =[dic objectForKey:#"phonesNum"];
}
}
else{
NSDictionary *dic=[[arr_searchContact objectAtIndex:indexPath.section]objectAtIndex:indexPath.row];
if ([[dic objectForKey:#"firstName"] length]>0) {
cell.textLabel.text = [dic objectForKey:#"firstName"];
}
else{
cell.textLabel.text =[dic objectForKey:#"phonesNum"];
}
}
cell.textLabel.textColor=[UIColor darkGrayColor];
cell.textLabel.highlightedTextColor = [UIColor whiteColor];
cell.textLabel.font=[UIFont fontWithName:#"OpenSans" size:14.0];
return cell;
}
You need to ensure that you only update the UI from the main queue. Your completion handler for the address book access will be executing on a background thread. Change the completion handler to invoke loadContacts on the main queue.
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
ABAddressBookRequestAccessWithCompletion(addressBook,
^(bool granted, CFErrorRef error) {
if (granted) {
dispatch_async(dispatch_get_main_queue(), ^{
[self loadContacts];
});
}
});
Related
I developed expandable and collapsed table view for dynamic data comes from the server. I'm displaying state names in header view successfully, but I can't displaying child data that is districts related to state names.
I followed Link for this http://www.iostute.com/2015/04/expandable-and-collapsable-tableview.html
My data is
_response = #{#"Response":#{#"status":#"SUCCESS",#"error_code":#"0",#"message":#"SUCCESS",#"Array":#[
#{#"state_id":#"0",#"state_name":#"null",#"district_id":#"0",#"district_name":#"null"},
#{#"state_id":#"01",#"state_name":#"State1",#"district_id":#"001",#"district_name":#"State1District1"},
#{#"state_id":#"02",#"state_name":#"State2",#"district_id":#"004",#"district_name":#"State2District1"},
#{#"state_id":#"02",#"state_name":#"State2",#"district_id":#"005",#"district_name":#"State3District1"},
#{#"state_id":#"01",#"state_name":#"State1",#"district_id":#"002",#"district_name":#"State1District2"},
#{#"state_id":#"01",#"state_name":#"State1",#"district_id":#"003",#"district_name":#"State1District3"},
#{#"state_id":#"03",#"state_name":#"State3",#"district_id":#"006",#"district_name":#"State3District1"},
#{#"state_id":#"04",#"state_name":#"State4",#"district_id":#"008",#"district_name":#"State4District1"},
#{#"state_id":#"04",#"state_name":#"State4",#"district_id":#"009",#"district_name":#"State4District2"},
#{#"state_id":#"04",#"state_name":#"State4",#"district_id":#"010",#"district_name":#"State4District3"},
#{#"state_id":#"05",#"state_name":#"State5",#"district_id":#"011",#"district_name":#"State5District1"},
#{#"state_id":#"05",#"state_name":#"State5",#"district_id":#"012",#"district_name":#"State5District2"},
#{#"state_id":#"03",#"state_name":#"State3",#"district_id":#"007",#"district_name":#"State3District2"}]}, #"count":#"6"};
My code is
if ([[[_response objectForKey:#"Response"] objectForKey:#"status"] isEqualToString:#"SUCCESS"] && (!(_integer == 0))) {
_stateID = [[NSMutableArray alloc] init];
_stateName = [[NSMutableArray alloc] init];
_districtID = [[NSMutableArray alloc] init];
_districtName = [[NSMutableArray alloc] init];
_stateIdStateNameDic = [[NSMutableDictionary alloc]init];
//Add arrays to array to remove null values dynamically
NSArray *arr = [[NSArray alloc]initWithObjects:_stateID, _stateName, _districtID, _districtName, nil];
for (int i=0; i<_integer; i++) {
[_stateID addObject:[[[[_response objectForKey:#"Response"] objectForKey:#"Array"] objectAtIndex:i] objectForKey:#"state_id"]];
[_stateName addObject:[[[[_response objectForKey:#"Response"] objectForKey:#"Array"] objectAtIndex:i] objectForKey:#"state_name"]];
[_districtID addObject:[[[[_response objectForKey:#"Response"] objectForKey:#"Array"] objectAtIndex:i] objectForKey:#"district_id"]];
[_districtName addObject:[[[[_response objectForKey:#"Response"] objectForKey:#"Array"] objectAtIndex:i] objectForKey:#"district_name"]];
//Remove null values
for (int j=0; j<arr.count; j++) {
for (NSMutableArray *ar in arr) {
if ([[ar objectAtIndex:i] isKindOfClass:[NSNull class]] || [[ar objectAtIndex:i] isEqualToString:#"null"] || [[ar objectAtIndex:i] isEqualToString:#"0"]) {
[ar addObject:#""];
[ar removeObjectAtIndex:i];
}
}
}
}
//Add arrays to mutable array to remove empty objects
NSMutableArray *marr = [[NSMutableArray alloc]initWithObjects:_stateID, _stateName, _districtID, _districtName, nil];
//Remove empty objects from all arrays
for (int j=0; j<marr.count; j++) {
for (int i=0; i<[[marr objectAtIndex:j] count]; i++) {
if ([[[marr objectAtIndex:j] objectAtIndex:i] isEqualToString:#""]) {
[[marr objectAtIndex:j] removeObjectAtIndex:i];
}
}
}
//Remove duplicates from state names array
_stateName = [_stateName valueForKeyPath:#"#distinctUnionOfObjects.self"];
NSString *districtName = #"";
NSString * superater = #"&&";
_mdic = [[NSMutableDictionary alloc]init];
for (int j=0; j<_stateName.count; j++) {
for (int i=0; i<_integer; i++) {
if ([[_stateName objectAtIndex:j] isEqualToString:[[[[_response objectForKey:#"Response"] objectForKey:#"Array"] objectAtIndex:i] objectForKey:#"state_name"]]) {
//Remove district name if empty or null
if ([districtName isEqualToString:#""] || [districtName isEqual:[NSNull null]]) {
districtName = [[[[_response objectForKey:#"Response"] objectForKey:#"Array"] objectAtIndex:i] objectForKey:#"district_name"];
if ([districtName isEqual:[NSNull null]] || [districtName isEqualToString:#"null"]) {
districtName = #"";
}
} else {
//Add all districts with superater &&
districtName = [districtName stringByAppendingString:[NSString stringWithFormat:#"%#%#", superater, [[[[_response objectForKey:#"Response"] objectForKey:#"Array"] objectAtIndex:i] objectForKey:#"district_name"]]];
}
}
}
//Create district names dictionary with state name keys
[_mdic setValue:districtName forKey:[_stateName objectAtIndex:j]];
districtName = #"";
}
NSLog(#"_mdic %#", _mdic);
_arrayForBool=[[NSMutableArray alloc]init];
//Save bool value " NO " based on sectionTitleArray count.
for (int i=0; i<[_stateName count]; i++) {
[_arrayForBool addObject:[NSNumber numberWithBool:NO]];
}
dispatch_async(dispatch_get_main_queue(), ^{
[_availableOrdersTableView reloadData];
});
} else {
}
// TableView delegates
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [_mdic count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Number of rows in each section
if ([[_arrayForBool objectAtIndex:section] boolValue]) {
NSLog(#"%#", [_stateName objectAtIndex:section]);
NSLog(#"%#", _mdic);
NSArray *mdicKeys = [_mdic allKeys];
for (int i=0; i<_mdic.count; i++) {
if ([[mdicKeys objectAtIndex:i] isEqualToString:[_stateName objectAtIndex:section]]) {
NSString *str = [_mdic objectForKey:[_stateName objectAtIndex:section]];
NSLog(#"%#", str);
_subDistrictArr = [str componentsSeparatedByString:#"&&"];
}
}
NSLog(#"_subDistrictIDArr %#", _subDistrictArr);
return _subDistrictArr.count;
} else {
return 0;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//Create cell
static NSString *cellid=#"cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellid];
if (cell==nil) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellid];
}
BOOL manyCells = [[_arrayForBool objectAtIndex:indexPath.section] boolValue];
/********** If the section supposed to be closed *******************/
if(!manyCells)
{
cell.backgroundColor=[UIColor clearColor];
cell.textLabel.text=#"";
}
/********** If the section supposed to be Opened *******************/
else {
cell.textLabel.text=[_subDistrictArr objectAtIndex:indexPath.row];
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
cell.textLabel.font=[UIFont systemFontOfSize:20.0f];
} else {
cell.textLabel.font=[UIFont systemFontOfSize:15.0f];
}
cell.backgroundColor=[UIColor whiteColor];
cell.selectionStyle=UITableViewCellSelectionStyleNone ;
}
cell.textLabel.textColor=[UIColor blackColor];
/********** Add a custom Separator with cell *******************/
UIView* separatorLineView = [[UIView alloc] initWithFrame:CGRectMake(15, 48, _availableOrdersTableView.frame.size.width-15, 1)];
separatorLineView.backgroundColor = [UIColor blackColor];
[cell.contentView addSubview:separatorLineView];
return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *sectionView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, _availableOrdersTableView.frame.size.width, 50)];
sectionView.backgroundColor = [UIColor clearColor];
sectionView.tag=section;
UILabel *viewLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, _availableOrdersTableView.frame.size.width, sectionView.frame.size.height)];
viewLabel.backgroundColor=[UIColor clearColor];
viewLabel.textColor=[UIColor blackColor];
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
viewLabel.font=[UIFont systemFontOfSize:25];
} else {
viewLabel.font=[UIFont systemFontOfSize:15];
}
viewLabel.text=[NSString stringWithFormat:#"%#", [_stateName objectAtIndex:section]];
_stateIDString = [_stateID objectAtIndex:section];
NSLog(#"stateIDString %#", _stateIDString);
[sectionView addSubview:viewLabel];
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(sectionView.frame.size.width-45, (sectionView.frame.size.height-25)/2, 18, 17)];
imgView.tag = section;
imgView.image = [UIImage imageNamed:#"DA"];
[sectionView addSubview:imgView];
} else {
UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(sectionView.frame.size.width-35, (sectionView.frame.size.height-25)/2, 18, 17)];
imgView.tag = section;
imgView.image = [UIImage imageNamed:#"DA"];
[sectionView addSubview:imgView];
}
/********** Add a custom Separator with Section view *******************/
UIView* separatorLineView = [[UIView alloc] initWithFrame:CGRectMake(0, sectionView.frame.size.height, _availableOrdersTableView.frame.size.width, 1)];
separatorLineView.backgroundColor = [UIColor blackColor];
[sectionView addSubview:separatorLineView];
/********** Add UITapGestureRecognizer to SectionView **************/
UITapGestureRecognizer *headerTapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(sectionHeaderTapped:)];
[sectionView addGestureRecognizer:headerTapped];
return sectionView;
}
- (void)sectionHeaderTapped:(UITapGestureRecognizer *)gestureRecognizer {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:gestureRecognizer.view.tag];
// _gestureInteger = gestureRecognizer.view.tag;
if (indexPath.row == 0) {
BOOL collapsed = [[_arrayForBool objectAtIndex:indexPath.section] boolValue];
for (int i=0; i<[_stateName count]; i++) {
if (indexPath.section==i) {
[_arrayForBool replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:!collapsed]];
}
}
[_availableOrdersTableView reloadSections:[NSIndexSet indexSetWithIndex:gestureRecognizer.view.tag] withRowAnimation:UITableViewRowAnimationAutomatic];
// [_availableOrdersTableView reloadData];
}
}
I have two solution for this
(1) initially you put numberofrow for any section is zero and after click on any section you can add row for for clicked section.
(2) number of section will be one and you need to use two cell "cellwithheaderonly" and "cellwithheaderandsubpart" initially you will use "cellwithheaderonly" and when user will click on any cell you need to use "cellwithheaderandsubpart"
You can take reference from following URL
Expanding and Collapsing table view cells in ios
https://www.anexinet.com/blog/expandable-collapsible-uitableview-sections/
You have to maintain an array given below : -
lat arr = [[“name”:”firstRow” , “subRowArray”:[1,2,3,4]],[“name”:”secondRow” , “subRowArray”:[1,2,3,4]],[“name”:”thirdRow” , “subRowArray”:[1,2,3,4]]]
then expand and collapse according to your array .
if would you like to use library then go for expendable Tableview
I am using UISegmentedControl and using UITableView but my query is segment button 1 click and display data for yes and 2 button click and display data from no and adding A to Z section UITableView first button click properly data display and properly tableview section atoz display but 2 button click and app crash `
#import "ZnameViewController.h"
#import "ZpaleoViewController.h"
#import "SWRevealViewController.h"
#interface ZnameViewController ()
#end
#implementation ZnameViewController
#synthesize strname1,sagmentController,objtbl,name;
- (void)viewDidLoad {
[super viewDidLoad];
SWRevealViewController *revealViewController = self.revealViewController;
if ( revealViewController )
{
[self.slide setTarget: self.revealViewController];
[self.slide setAction: #selector( revealToggle: )];
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
}
appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
databse = [FMDatabase databaseWithPath:appdelegate.appDBPath];
[arrCatname removeAllObjects];
[arrPaleo removeAllObjects];
arrCatname = [[NSMutableArray alloc]init];
arrPaleo = [[NSMutableArray alloc]init];
arrStatus = [[NSMutableArray alloc]init];
arrCat2 = [[NSMutableArray alloc]init];
arrSta2 = [[NSMutableArray alloc]init];
[self segmentSwitch:self];
// Do any additional setup after loading the view.
}
- (IBAction)segmentSwitch:(id)sender {
[databse open];
NSString *selectQuery = [NSString stringWithFormat:#"select * from Food ORDER BY name ASC"];
NSLog(#"%#",selectQuery);
FMResultSet *resultQuary = [databse executeQuery:selectQuery];
while ([resultQuary next]) {
// NSString *z_paleo = [resultQuary stringForColumn:#"status"];
z_paleo = [NSString stringWithFormat:#"%d",[resultQuary intForColumn:#"status"]];
if ([z_paleo isEqualToString:#"1"]) {
if(z_name == nil || [z_name isKindOfClass:[NSNull null]])
{
[arrPaleo addObject:#""];
}
else{
[arrPaleo addObject:z_name];
}
[arrSta2 addObject:z_paleo];
}
else{
if(z_name == nil || [z_name isKindOfClass:[NSNull null]])
{
[arrCatname addObject:#""];
}
else
{
[arrCatname addObject:z_name];
}
[arrCat2 addObject:z_paleo];
}
}
[databse close];
if(sagmentController.selectedSegmentIndex == 0)
{
if ([z_paleo isEqualToString:#"1"]) {
[self getName:arrPaleo];
objtbl.hidden = NO;
}
}
else if (sagmentController.selectedSegmentIndex == 1)
{
if ([z_paleo isEqualToString:#"0"]) {
[self getName:arrCatname];
objtbl.hidden = NO;
}
}
[objtbl reloadData];
}
-(void)getName:(NSMutableArray *)arr
{
NSMutableArray *temp = [[NSMutableArray alloc] init];
NSMutableArray *temp2 = [[NSMutableArray alloc] init];
for(int i = 0; i < arr.count; i++)
{
NSString *string = [arr objectAtIndex:i];
dict = [[NSMutableDictionary alloc] init];
[dict setObject:string forKey:#"Name"];
[dict setObject:[NSNumber numberWithInt:i] forKey:#"ID"];
NSString *firstString = [string substringToIndex:1];
if([temp2 containsObject:firstString] == NO || temp2.count == 0)
{
if(temp2.count != 0)
{
[temp addObject:temp2];
temp2 = [[NSMutableArray alloc] init];
}
[temp2 addObject:firstString];
}
[temp2 addObject:dict];
}
[temp addObject:temp2];
sorted = [[NSArray alloc] initWithArray:temp];
}
-(void)getname2:(NSMutableArray *)array{
NSMutableArray *temp = [[NSMutableArray alloc] init];
NSMutableArray *temp2 = [[NSMutableArray alloc] init];
for(int i = 0; i < array.count; i++)
{
NSString *string = [array objectAtIndex:i];
dict1 = [[NSMutableDictionary alloc] init];
[dict1 setObject:string forKey:#"Name"];
[dict1 setObject:[NSNumber numberWithInt:i] forKey:#"ID"];
NSString *firstString = [string substringToIndex:1];
if([temp2 containsObject:firstString] == NO || temp2.count == 0)
{
if(temp2.count != 0)
{
[temp addObject:temp2];
temp2 = [[NSMutableArray alloc] init];
}
[temp2 addObject:firstString];
}
[temp2 addObject:dict1];
}
[temp addObject:temp2];
sorted1 = [[NSArray alloc] initWithArray:temp];
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
int i = 0;
for(NSArray *array in sorted)
{
NSString *string = [array objectAtIndex:0];
if([string compare:title] == NSOrderedSame)
break;
i++;
}
return i;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if (sagmentController.selectedSegmentIndex == 0) {
return [sorted count];
}else {
return [sorted count];
}
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSArray *array = [sorted objectAtIndex:section];
return [array objectAtIndex:0];
//return [foodIndexTitles objectAtIndex:section];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
NSMutableArray *titleArray = [NSMutableArray array];
[titleArray addObject:#"A"];
[titleArray addObject:#"B"];
[titleArray addObject:#"C"];
[titleArray addObject:#"D"];
[titleArray addObject:#"E"];
[titleArray addObject:#"F"];
[titleArray addObject:#"G"];
[titleArray addObject:#"H"];
[titleArray addObject:#"I"];
[titleArray addObject:#"J"];
[titleArray addObject:#"K"];
[titleArray addObject:#"L"];
[titleArray addObject:#"M"];
[titleArray addObject:#"N"];
[titleArray addObject:#"O"];
[titleArray addObject:#"P"];
[titleArray addObject:#"Q"];
[titleArray addObject:#"R"];
[titleArray addObject:#"S"];
[titleArray addObject:#"T"];
[titleArray addObject:#"U"];
[titleArray addObject:#"V"];
[titleArray addObject:#"W"];
[titleArray addObject:#"X"];
[titleArray addObject:#"Y"];
[titleArray addObject:#"Z"];
return titleArray;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if (sagmentController.selectedSegmentIndex == 1) {
NSArray *array = [sorted objectAtIndex:section];
return (array.count - 1);
}else{
NSArray *array = [sorted objectAtIndex:section];
return (array.count - 1);
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifire = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifire];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifire];
}
if (sagmentController.selectedSegmentIndex == 0) {
NSArray *array = [sorted objectAtIndex:indexPath.section];
dict = [array objectAtIndex:indexPath.row + 1];
cell.textLabel.text = [dict objectForKey:#"Name"];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"Yes_check.png"]];
[cell.accessoryView setFrame:CGRectMake(0, 0, 15, 15)];
}
else
{
NSArray *array = [sorted objectAtIndex:indexPath.section];
dict = [array objectAtIndex:indexPath.row + 1];
cell.textLabel.text = [dict objectForKey:#"Name"];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"No.png"]];
[cell.accessoryView setFrame:CGRectMake(0, 0, 15, 15)];
return cell;
}
return cell;
}
When I am reloading a TableView only some data is showing in cells and when I touch, it is showing all the data in table. I used content offset of table view as 0,0
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//Searching code
if (isSearching)
{
if ([arrCopyListOfItems count])
return [arrIndex count];
else
return 1;
}
//filtering code
else if (isFiltering)
{
if ([arrayFilterdContacts count])
return [arrIndex count];
else
return 1;
}
else
{
if([appDelegate.arrayContactsFromDb count])
return [arrIndex count];
else
return 1;
}
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
if (isSearching)
{
if ([arrCopyListOfItems count])
{
NSString *alphabet = [arrIndex objectAtIndex:section];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"contactName beginswith[c]%#",alphabet];
NSArray *sort = [arrCopyListOfItems filteredArrayUsingPredicate:predicate];
return [sort count];
}
else
return 1;
}
else if(isFiltering)
{
if ([arrayFilterdContacts count])
{
NSString *alphabet = [arrIndex objectAtIndex:section];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"contactName beginswith[c]%#",alphabet];
NSArray *sort = [arrayFilterdContacts filteredArrayUsingPredicate:predicate];
return [sort count];
}
else
return 1;
}
else
{
NSString *alphabet = [arrIndex objectAtIndex:section];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"contactName beginswith[c]%#",alphabet];
NSArray *sort = [appDelegate.arrayContactsFromDb filteredArrayUsingPredicate:predicate];
return [sort count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
UITableViewCell *cell = [[UITableViewCell alloc] init];
cell.textLabel.backgroundColor=[UIColor clearColor];
cell.textLabel.font = [UIFont systemFontOfSize:14];
cell.backgroundColor = [UIColor clearColor];
Contacts *objContact;
//Changing colors
if (indexPath.row % 2 == 0)
{
cell.contentView.backgroundColor = [UIColor colorWithRed:245.0/255.0 green:245.0/255.0 blue:245.0/255.0 alpha:1.0];
}
else
{
cell.contentView.backgroundColor = [UIColor colorWithRed:232.0/255.0 green:232.0/255.0 blue:232.0/255.0 alpha:1.0];
}
UILongPressGestureRecognizer *longPressGesture =
[[UILongPressGestureRecognizer alloc]
initWithTarget:self action:#selector(longPress:)] ;
[cell addGestureRecognizer:longPressGesture];
//Local Searching Table View
if (isSearching)
{
if([arrCopyListOfItems count])
{
NSString *alphabet = [arrIndex objectAtIndex:[indexPath section]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"contactName beginswith[c]%#",alphabet];
NSArray *arysortContact = [arrCopyListOfItems filteredArrayUsingPredicate:predicate];
objContact = [arysortContact objectAtIndex:indexPath.row];
}
else
{
cell.textLabel.text = kNoSearchResult;
cell.textLabel.textAlignment = NSTextAlignmentCenter;
return cell;
}
}
//Contacts Table View WithOut Searching and showing filtering
else
{
cell.textLabel.frame = CGRectMake(2, 3, 35, 30);
//Showing filtering list
if (isFiltering)
{
if ([arrayFilterdContacts count])
{
NSString *alphabet = [arrIndex objectAtIndex:[indexPath section]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"contactName beginswith[c]%#",alphabet];
NSArray *arysortContact = [arrayFilterdContacts filteredArrayUsingPredicate:predicate];
objContact = [arysortContact objectAtIndex:indexPath.row];
}
else
{
cell.textLabel.text = kContactFilter;
cell.textLabel.textAlignment = NSTextAlignmentCenter;
return cell;
}
}
//Showing all the contacts list
else
{
NSString *alphabet = [arrIndex objectAtIndex:[indexPath section]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"contactName beginswith[c]%#",alphabet];
NSArray *arysortContact = [appDelegate.arrayContactsFromDb filteredArrayUsingPredicate:predicate];
if ([arysortContact count])
{
objContact = [arysortContact objectAtIndex:indexPath.row];
}
}
}
//Displaying name of a contact
UILabel *lblName;
if([objContact.contactName length ]> 0)
{
lblName = [self createLabelWithTitle:[NSString stringWithFormat:#"%# %#",objContact.contactName,objContact.lastName] frame:CGRectMake(15, 0, 150, 60) tag:10 font:fontMyriad color:[UIColor colorWithRed:40.0/255.0 green:40.0/255.0 blue:40.0/255.0 alpha:1] numberOfLines:1];
}
else
{
lblName = [self createLabelWithTitle:objContact.phoneNumber frame:CGRectMake(15, 0, 150, 60) tag:10 font:fontMyriad color:[UIColor colorWithRed:40.0/255.0 green:40.0/255.0 blue:40.0/255.0 alpha:1] numberOfLines:1];
}
lblName.backgroundColor=[UIColor clearColor];
lblName.textAlignment = NSTextAlignmentLeft;
lblName.numberOfLines=10000;
lblName.lineBreakMode=NSLineBreakByWordWrapping;
//Showing different color for users
if ([objContact.Id integerValue] != 0 || objContact.businessInfo)
{
lblName.textColor = [UIColor blueColor];
}
[cell.contentView addSubview:lblName];
//Displaying all tags for a contact
NSMutableArray *arrTags = [(NSMutableArray*)[objContact.contactsToTagMaster allObjects] mutableCopy];
NSSortDescriptor *valueDescriptor = [[NSSortDescriptor alloc] initWithKey:#"tagName" ascending:YES];
NSArray * descriptors = [NSArray arrayWithObject:valueDescriptor];
arrTags = (NSMutableArray*)[arrTags sortedArrayUsingDescriptors:descriptors];
float floatTagsHeight= [self getTagNameHeight:arrTags];
if ([arrTags count]>2) {
lblName.frame=CGRectMake(10, 0, 150, floatTagsHeight+[arrTags count]*2+4);
}
UIScrollView *scrollVwForImage=[[UIScrollView alloc]initWithFrame:CGRectMake(200, 2, 80, floatTagsHeight+[arrTags count]*2+10)];
scrollVwForImage.backgroundColor =[UIColor clearColor];
if (isOpened) {
if ([arrTags count]>2)
lblName.frame=CGRectMake(lblName.frame.origin.x, lblName.frame.origin.y, 115, floatTagsHeight+[arrTags count]*2+4);
float floatTagsHeight= [self getTagNameHeight:arrTags];
scrollVwForImage.frame=CGRectMake(130, 2, 80, floatTagsHeight+[arrTags count]*2+10);
}
if(objContact.contactsToTagMaster != nil)
{
int intHeight=2;
for(int i=0;i< [arrTags count];i++)
{
//If Tag short name is present
if([[[arrTags objectAtIndex:i]valueForKey:#"tagName"] length])
{
CGSize size= [[[arrTags objectAtIndex:i]valueForKey:#"tagName"] sizeWithFont:fontMyriad constrainedToSize:CGSizeMake(70, 1000) lineBreakMode:NSLineBreakByWordWrapping];
float floatTagHeight=(size.height>15)?size.height:15;
UIImageView *imageViewBox = [[UIImageView alloc] initWithFrame:CGRectMake(0, intHeight, 80, floatTagHeight)];
imageViewBox.backgroundColor=[UIColor colorWithRed:211.0/255.0 green:211.0/255.0 blue:211.0/255.0 alpha:1.0];
[scrollVwForImage addSubview:imageViewBox];
UILabel *lblTagShortName = [[UILabel alloc]initWithFrame:CGRectMake(5, 0, 75, floatTagHeight)];
lblTagShortName.backgroundColor = [UIColor clearColor];
lblTagShortName.text = [[arrTags objectAtIndex:i]valueForKey:#"tagName"];
[lblTagShortName setFont:fontMyriad];
lblTagShortName.textColor = [UIColor colorWithRed:125.0/255.0 green:129.0/255.0 blue:135.0/255.0 alpha:1] ;
lblTagShortName.autoresizesSubviews = YES;
lblTagShortName.textAlignment = NSTextAlignmentLeft;
lblTagShortName.lineBreakMode=NSLineBreakByWordWrapping;
lblTagShortName.numberOfLines=1000;
//lblTagShortName.adjustsFontSizeToFitWidth=YES;
[imageViewBox addSubview:lblTagShortName];
intHeight+=floatTagHeight+2;
}
}
}
[cell.contentView addSubview:scrollVwForImage];
}
return cell;
}
When i click search it executes a search class and after finding the results it executes numberOfRows method but then it is showing empty table. It is not executing cellForRowAtIndexPath method .
check my below code
code in viewcontroller.h
when i click search button this method will get executed
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
SearchResultsViewController *searchRes=[[SearchResultsViewController alloc]initWithNibName:#"SearchResultsViewController" bundle:nil];
NSString *searchQuery=[search text];
sharedManager=[Mymanager sharedManager];
sharedManager.searchQuery=searchQuery;
[searchRes searchString:searchQuery];
[self.navigationController pushViewController:searchRes animated:YES];
}
in search class
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSLog(#"%#",results);
return [results count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView1 cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView1 dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.textLabel.adjustsFontSizeToFitWidth = YES;
NSLog(#"indexpath%d",indexPath.row);
NSLog(#"%#",[results objectAtIndex:[indexPath row]]);
SearchResult* hit = (SearchResult*)[results objectAtIndex:[indexPath row]];
NSLog(#"%#",hit.neighboringText);
cell.textLabel.text = [NSString stringWithFormat:#"...%#...", hit.neighboringText];
cell.detailTextLabel.text = [NSString stringWithFormat:#"Chapter %d - page %d", hit.chapterIndex, hit.pageIndex+1];
cell.textLabel.font = [UIFont fontWithName:#"Trebuchet MS" size:12];
cell.textLabel.textColor = [UIColor colorWithRed:25/255.0 green:90/255.0 blue:100/255.0 alpha:1];
// else
// {
//
// }
// [[self resultsTableView] reloadData];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
SearchResult* hit = (SearchResult*)[results objectAtIndex:[indexPath row]];
[fvc loadSpine:hit.chapterIndex atPageIndex:hit.pageIndex highlightSearchResult:hit];
}
- (void) searchString:(NSString*)query{
// if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
// {
self.results = [[NSMutableArray alloc] init];
[resultsTableView reloadData];
currentQuery=sharedManager.searchQuery;
//
[self searchString:currentQuery inChapterAtIndex:0];
//
// }else {
// currentQuery=sharedManager.searchQuery;
// [self searchString:currentQuery inChapterAtIndex:0];
//}
}
- (void) searchString:(NSString *)query inChapterAtIndex:(int)index{
currentChapterIndex = index;
sharedManager=[Mymanager sharedManager];
Chapter* chapter = [sharedManager.spineArray objectAtIndex:index];
NSLog(#"%d",chapter.text.length);
NSRange range = NSMakeRange(0, chapter.text.length);
NSLog(#"%#",sharedManager.searchQuery);
range = [chapter.text rangeOfString:sharedManager.searchQuery options:NSCaseInsensitiveSearch range:range locale:nil];
int hitCount=0;
while (range.location != NSNotFound) {
range = NSMakeRange(range.location+range.length, chapter.text.length-(range.location+range.length));
range = [chapter.text rangeOfString:sharedManager.searchQuery options:NSCaseInsensitiveSearch range:range locale:nil];
hitCount++;
}
if(hitCount!=0){
UIWebView* webView = [[UIWebView alloc] initWithFrame:chapter.windowSize];
[webView setDelegate:self];
NSURLRequest* urlRequest = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:chapter.spinePath]];
[webView loadRequest:urlRequest];
} else {
if((currentChapterIndex+1)<[sharedManager.spineArray count]){
[self searchString:sharedManager.searchQuery inChapterAtIndex:(currentChapterIndex+1)];
} else {
fvc.searching = NO;
}
}
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
NSLog(#"%#", error);
[webView release];
}
- (void) webViewDidFinishLoad:(UIWebView*)webView{
NSString *varMySheet = #"var mySheet = document.styleSheets[0];";
NSString *addCSSRule = #"function addCSSRule(selector, newRule) {"
"if (mySheet.addRule) {"
"mySheet.addRule(selector, newRule);" // For Internet Explorer
"} else {"
"ruleIndex = mySheet.cssRules.length;"
"mySheet.insertRule(selector + '{' + newRule + ';}', ruleIndex);" // For Firefox, Chrome, etc.
"}"
"}";
NSString *insertRule1 = [NSString stringWithFormat:#"addCSSRule('html', 'padding: 0px; height: %fpx; -webkit-column-gap: 0px; -webkit-column-width: %fpx;')", webView.frame.size.height, webView.frame.size.width];
NSString *insertRule2 = [NSString stringWithFormat:#"addCSSRule('p', 'text-align: justify;')"];
NSString *setTextSizeRule = [NSString stringWithFormat:#"addCSSRule('body', '-webkit-text-size-adjust: %d%%;')",[[sharedManager.spineArray objectAtIndex:currentChapterIndex] fontPercentSize]];
[webView stringByEvaluatingJavaScriptFromString:varMySheet];
[webView stringByEvaluatingJavaScriptFromString:addCSSRule];
[webView stringByEvaluatingJavaScriptFromString:insertRule1];
[webView stringByEvaluatingJavaScriptFromString:insertRule2];
[webView stringByEvaluatingJavaScriptFromString:setTextSizeRule];
[webView highlightAllOccurencesOfString:sharedManager.searchQuery];
NSString* foundHits = [webView stringByEvaluatingJavaScriptFromString:#"results"];
NSLog(#"%#", foundHits);
NSMutableArray* objects = [[NSMutableArray alloc] init];
NSArray* stringObjects = [foundHits componentsSeparatedByString:#";"];
for(int i=0; i<[stringObjects count]; i++){
NSArray* strObj = [[stringObjects objectAtIndex:i] componentsSeparatedByString:#","];
if([strObj count]==3){
[objects addObject:strObj];
}
}
NSArray* orderedRes = [objects sortedArrayUsingComparator:^(id obj1, id obj2){
int x1 = [[obj1 objectAtIndex:0] intValue];
int x2 = [[obj2 objectAtIndex:0] intValue];
int y1 = [[obj1 objectAtIndex:1] intValue];
int y2 = [[obj2 objectAtIndex:1] intValue];
if(y1<y2){
return NSOrderedAscending;
} else if(y1>y2){
return NSOrderedDescending;
} else {
if(x1<x2){
return NSOrderedAscending;
} else if (x1>x2){
return NSOrderedDescending;
} else {
return NSOrderedSame;
}
}
}];
[objects release];
NSLog(#"%#",currentQuery);
for(int i=0; i<[orderedRes count]; i++){
NSArray* currObj = [orderedRes objectAtIndex:i];
SearchResult* searchRes = [[SearchResult alloc] initWithChapterIndex:currentChapterIndex pageIndex:([[currObj objectAtIndex:1] intValue]/webView.bounds.size.height) hitIndex:0 neighboringText:[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:#"unescape('%#')", [currObj objectAtIndex:2]]] originatingQuery:currentQuery];
[results addObject:searchRes];
NSLog(#"%#",results);
[searchRes release];
}
//Print results
for(int i=0;i<[results count];i++)
{
SearchResult* hit = (SearchResult*)[results objectAtIndex:i];
NSLog(#"%#",hit.neighboringText);
}
[resultsTableView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:NO];
if((currentChapterIndex+1)<[sharedManager.spineArray count]){
[self searchString:sharedManager.searchQuery inChapterAtIndex:(currentChapterIndex+1)];
} else {
fvc.searching= NO;
}
[[self resultsTableView] reloadData];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
//- (void)dealloc
////{
//// self.resultsTableView = nil;
//// //[results release];
//// //[currentQuery release];
//// [super dealloc];
//}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
resultsTableView=[[UITableView alloc]init];
[resultsTableView setDelegate:self];
[resultsTableView setDataSource:self];
sharedManager=[Mymanager sharedManager];
// Do any additional setup after loading the view from its nib.
results = [[NSMutableArray alloc] init];
self.navigationItem.title=#"Search ";
UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
initWithTitle:#"Back"
style:UIBarButtonItemStylePlain
target:nil
action:nil];
self.navigationItem.backBarButtonItem=backButton;
[[UINavigationBar appearance] setTitleTextAttributes: #{
UITextAttributeTextColor: [UIColor whiteColor],
UITextAttributeTextShadowColor: [UIColor lightGrayColor],
UITextAttributeTextShadowOffset: [NSValue valueWithUIOffset:UIOffsetMake(0.0f, 1.0f)],
UITextAttributeFont: [UIFont fontWithName:#"Trebuchet MS" size:15.0f]
}];
noMatchingSearch=[[NSArray alloc]initWithObjects:#"No Element Found", nil];
tableOfContents=[[NSMutableArray alloc]init];
for (id img in search.subviews)
{
if ([img isKindOfClass:NSClassFromString(#"UISearchBarBackground")])
{
[img removeFromSuperview];
}
}
tableOfContents=[sharedManager.List copy];
}
- (void)viewDidUnload
{
search = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
self.resultsTableView = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
MY SEARCH RESULTS
"<SearchResult: 0x113482c0>",
"<SearchResult: 0x11348a20>",
"<SearchResult: 0x88c0a50>"
The problem is with the search method before search the array is reinitialised and hence 0 returned in the resultArray and hence no value in tables
- (void) searchString:(NSString*)query{
self.results = [[NSMutableArray alloc] init];//Here it becomes 0!!
[resultsTableView reloadData];
currentQuery=sharedManager.searchQuery;
}
To make it right ,After the search is performed i believe
[self searchString:currentQuery inChapterAtIndex:0];
load the value in the result array and then reload table.
Make sure
in .h add
<UITableViewDataSource,UITableViewDelegate>
in nib
connect datasource and delegate[if via nib]
Rows of Level 1 should expand and collapse. Suppose if Row 0 is open - that means its status is 1 - and next row's status is 0, if I click on next row whose status is 0, then the row whose status is 1 should get closed.
How can I do that?
Here is my code:
- (void)viewDidLoad {
[super viewDidLoad];
dictBtnStatus = [[NSMutableDictionary alloc] init];
arraylist = [[NSMutableArray alloc] init];
array5 = [[NSMutableArray alloc] init];
array1 = [[NSMutableArray alloc] init];
objects = #[#"Medical Services In Chicago", #"Medical Services On Campus", #"ABC", #"California"];
// objects = #[#"Medical Services In Chicago", #"Medical Services On Campus"];
arrObjectValueChicago = #[#"Ronald McDonald® Children's Hospital of Loyola", #"Burn Centers", #"Gottlieb Hospitals"];
arrObjectValueCampus = #[#"Cardinal Bernardin Cancer Center1", #"Center for Heart & Vascular Medicine2", #"ABC"];
for (int i = 0; i < [arrObjectValueCampus count]; i++) {
dictListCampus1 = [[NSDictionary alloc] initWithObjectsAndKeys:#"2", #"level",[arrObjectValueCampus objectAtIndex:i], #"name", nil];
[array5 addObject:dictListCampus1];
}
NSDictionary *dictListCampus = [[NSDictionary alloc] initWithObjectsAndKeys:#"Wellness Centers", #"name", #"1", #"level", array5, #"Objects", nil];
NSMutableArray *array6 = [[NSMutableArray alloc] initWithObjects:dictListCampus, nil];
array3 = [[NSMutableArray alloc] init ];
for (int i = 0; i < [arrObjectValueChicago count]; i++){
dictList3 = [[NSDictionary alloc]initWithObjectsAndKeys:#"2", #"level",[arrObjectValueChicago objectAtIndex:i], #"name", nil];
[array3 addObject:dictList3];
}
NSDictionary *dictList2 = [[NSDictionary alloc] initWithObjectsAndKeys:#"Hospitals", #"name", #"1", #"level", array3, #"Objects", nil];
NSMutableArray *array2 = [[NSMutableArray alloc] initWithObjects:dictList2, nil];
for (int i = 0; i < [objects count]; i++) {
if (i == 0) {
dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:[objects objectAtIndex:0], #"name", #"0", #"level", array2, #"Objects", nil];
[array1 addObject:dictionary];
} else if (i == 1) {
dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:[objects objectAtIndex:1], #"name", #"0", #"level", array6, #"Objects", nil];
[array1 addObject:dictionary];
} else if (i == 2) {
dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:[objects objectAtIndex:2], #"name", #"0", #"level", array6, #"Objects", nil];
[array1 addObject:dictionary];
} else {
dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:[objects objectAtIndex:3], #"name", #"0", #"level", array2, #"Objects", nil];
[array1 addObject:dictionary];
}
}
dictList = [[NSDictionary alloc] initWithObjectsAndKeys:array1, #"Objects", nil];
arrayOriginal = [dictList valueForKey:#"Objects"];
[arraylist addObjectsFromArray:arrayOriginal];
}
#pragma mark - TableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [arraylist count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// static NSString *CellIdentifier = #"CustomCellIdentifier";
NSUInteger IndentLevel = [[[arraylist objectAtIndex:indexPath.row] valueForKey:#"level"] intValue];
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (IndentLevel == 0) {
CustomCellHeader *cell = (CustomCellHeader *)[tableView dequeueReusableCellWithIdentifier:#"CellIdentifier"];
if (cell == nil) {
[[NSBundle mainBundle]loadNibNamed:#"CustomCellHeader" owner:self options:nil];
cell = self.headercell;
self.headercell = nil;
}
cell.lblHeader.text = [[arraylist objectAtIndex:indexPath.row] valueForKey:#"name"];
[cell setIndentationLevel:[[[arraylist objectAtIndex:indexPath.row] valueForKey:#"level"] intValue]];
NSLog(#"indexFor level 0 ::%# %d",cell.lblHeader.text,indexPath.row);
return cell;
} else if (IndentLevel == 1) {
CustomCellSubHeader *cell = (CustomCellSubHeader *)[tableView dequeueReusableCellWithIdentifier:#"CellIdentifier"];
if (!cell) {
[[NSBundle mainBundle]loadNibNamed:#"CustomCellSubHeader" owner:self options:nil];
cell = self.subheadercell;
self.subheadercell = nil;
NSLog(#"dicbtn %#", dictBtnStatus);
NSString *strName = [[arraylist objectAtIndex:indexPath.row]valueForKey:#"name"];
NSString *str = [dictBtnStatus objectForKey:strName];
NSLog(#"indexFor level 1 ::%# %d", strName, indexPath.row);
if ([str isEqualToString:#"1"]) {
[cell.btnarrow setImage:[UIImage imageNamed:#"dwn1_arow.png"] forState:UIControlStateNormal];
[cell.imgSubHeader setImage:[UIImage imageNamed:#"tab_active.png"]];
}
cell.lblSubHeader.text = strName;
cell.imgShadow.hidden = YES;
[cell setIndentationLevel:[[[arraylist objectAtIndex:indexPath.row] valueForKey:#"level"] intValue]];
}
return cell;
} else if (IndentLevel == 2) {
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:#"CellIdentifier"];
if (cell == nil) {
[[NSBundle mainBundle]loadNibNamed:#"CustomCell" owner:self options:nil];
cell = self.cells;
self.cells = nil;
}
cell.txtAddress.text = [[arraylist objectAtIndex:indexPath.row] valueForKey:#"name"];
[cell.btnCall addTarget:self action:#selector(btnCall:) forControlEvents:UIControlEventTouchUpInside];
[cell setIndentationLevel:[[[arraylist objectAtIndex:indexPath.row] valueForKey:#"level"] intValue]];
return cell;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tblist deselectRowAtIndexPath:indexPath animated:YES];
NSUInteger IndentLevel = [[[arraylist objectAtIndex:indexPath.row] valueForKey:#"level"] intValue];
NSString *strName = [[arraylist objectAtIndex:indexPath.row] valueForKey:#"name"];
CustomCellSubHeader *cell = ((CustomCellSubHeader*)[tblist cellForRowAtIndexPath:indexPath]);
if (IndentLevel == 1) {
[dictBtnStatus setValue:#"0" forKey:strName];
[cell.btnarrow setImage:[UIImage imageNamed:#"gry_arrow.png"] forState:UIControlStateNormal];
[cell.imgSubHeader setImage:[UIImage imageNamed:#"tab_default.png"]];
}
NSDictionary *d = [arraylist objectAtIndex:indexPath.row];
if ([d valueForKey:#"Objects"]) {
NSArray *ar = [d valueForKey:#"Objects"];
BOOL isAlreadyInserted = NO;
for (NSDictionary *dInner in ar) {
NSInteger index = [arraylist indexOfObjectIdenticalTo:dInner];
isAlreadyInserted = (index > 0 && index != NSIntegerMax);
if (IndentLevel == 1) {
[dictBtnStatus setValue:#"0" forKey:strName];
[cell.btnarrow setImage:[UIImage imageNamed:#"gry_arrow.png"] forState:UIControlStateNormal];
[cell.imgSubHeader setImage:[UIImage imageNamed:#"tab_default.png"]];
} else if (IndentLevel == 0) {
NSString *strStatus = [dictBtnStatus objectForKey:strName];
if ([strStatus isEqualToString:#"1"]) {
// NSDictionary *dict = [arraylist objectAtIndex:previousRow];
// if ([dict valueForKey:#"Objects"]) {
NSArray * array = [[arraylist objectAtIndex:previousRow]valueForKey:#"Objects"];
[self miniMizeThisRows:array];
}
}
if (isAlreadyInserted) break;
}
if (isAlreadyInserted) {
if ([arraylist count] - 1 && IndentLevel == 1) {
cell.imgShadow.hidden = NO;
}
if (IndentLevel == 1) {
[dictBtnStatus setValue:#"0" forKey:strName];
[cell.btnarrow setImage:[UIImage imageNamed:#"gry_arrow.png"] forState:UIControlStateNormal];
[cell.imgSubHeader setImage:[UIImage imageNamed:#"tab_default.png"]];
} else if (IndentLevel == 0) {
[dictBtnStatus setValue:#"0" forKey:strName];
}
[self miniMizeThisRows:ar];
} else {
NSUInteger count=indexPath.row + 1;
NSMutableArray *arCells = [NSMutableArray array];
for (NSDictionary *dInner in ar) {
[arCells addObject:[NSIndexPath indexPathForRow:count inSection:0]];
previousRow = [indexPath row];
if (IndentLevel == 1) {
[dictBtnStatus setValue:#"1" forKey:strName];
[cell.btnarrow setImage:[UIImage imageNamed:#"dwn1_arow.png"] forState:UIControlStateNormal];
[cell.imgSubHeader setImage:[UIImage imageNamed:#"tab_active.png"]];
} else if (IndentLevel == 0) {
[dictBtnStatus setValue:#"1" forKey:strName];
}
[arraylist insertObject:dInner atIndex:count++];
}
[tableView insertRowsAtIndexPaths:arCells withRowAnimation:UITableViewRowAnimationNone];
}
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger indentLevel = [[[arraylist objectAtIndex:indexPath.row] valueForKey:#"level"] intValue];
if (indentLevel == 0) {
return 40;
} else if (indentLevel == 1) {
return 25;
} else if (indentLevel == 2) {
CustomCell *cell = ((CustomCell *)[tableView dequeueReusableCellWithIdentifier:#"CellIdentifier"]);
CGSize maximumSize = CGSizeMake(300, 9999);
UIFont *myFont = [UIFont fontWithName:#"Arial" size:11.5];
CGSize myStringSize = [cell.txtAddress.text sizeWithFont:myFont constrainedToSize:maximumSize lineBreakMode:NSLineBreakByWordWrapping];
[cell.txtAddress setFrame:CGRectMake(cell.txtAddress.frame.origin.x, cell.txtAddress.frame.origin.y, cell.txtAddress.frame.size.width, myStringSize.height)];
if (myStringSize.height > 80) {
myStringSize.height = 50;
[cell.txtAddress setFrame:CGRectMake(cell.txtAddress.frame.origin.x, cell.txtAddress.frame.origin.y, cell.txtAddress.frame.size.width, myStringSize.height)];
cell.txtAddress.scrollEnabled = YES;
} else {
cell.txtAddress.scrollEnabled = YES;
myStringSize.height = 40;
}
return myStringSize.height+ 50;
} else return 25;
}
#pragma mark - TableAnimation
- (void)miniMizeThisRows:(NSArray *)ar {
for(NSDictionary *dInner in ar) {
NSUInteger indexToRemove = [arraylist indexOfObjectIdenticalTo:dInner];
NSArray *arInner = [dInner valueForKey:#"Objects"];
if (arInner && [arInner count] > 0) {
[self miniMizeThisRows:arInner];
}
if ([arraylist indexOfObjectIdenticalTo:dInner]!= NSNotFound) {
[arraylist removeObjectIdenticalTo:dInner];
[tblist deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:indexToRemove inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}
}
}
- (void)viewDidLoad {
[super viewDidLoad];
dictBtnStatus = [[NSMutableDictionary alloc] init];
arraylist = [[NSMutableArray alloc] init];
array5 = [[NSMutableArray alloc] init];
array1 = [[NSMutableArray alloc] init];
objects = #[#"Medical Services In Chicago", #"Medical Services On Campus", #"ABC", #"California"];
// objects = #[#"Medical Services In Chicago", #"Medical Services On Campus"];
arrObjectValueChicago = #[#"Ronald McDonald® Children's Hospital of Loyola", #"Burn Centers", #"Gottlieb Hospitals"];
arrObjectValueCampus = #[#"Cardinal Bernardin Cancer Center1", #"Center for Heart & Vascular Medicine2", #"ABC"];
for (int i = 0; i < [arrObjectValueCampus count]; i++) {
dictListCampus1 = [[NSDictionary alloc]initWithObjectsAndKeys:#"2", #"level",[arrObjectValueCampus objectAtIndex:i], #"name", nil];
[array5 addObject:dictListCampus1];
}
NSDictionary *dictListCampus = [[NSDictionary alloc]initWithObjectsAndKeys:#"Wellness Centers", #"name", #"1", #"level", array5, #"Objects", nil];
NSMutableArray *array6 = [[NSMutableArray alloc] initWithObjects:dictListCampus, nil];
NSDictionary *dictListCampus2 = [[NSDictionary alloc] initWithObjectsAndKeys:#"Wellness Centers123", #"name", #"1", #"level", array5, #"Objects", nil];
NSMutableArray *array61 = [[NSMutableArray alloc] initWithObjects:dictListCampus2, nil];
array3 = [[NSMutableArray alloc] init];
for (int i = 0; i < [arrObjectValueChicago count]; i++) {
dictList3 = [[NSDictionary alloc] initWithObjectsAndKeys:#"2", #"level",[arrObjectValueChicago objectAtIndex:i], #"name", nil];
[array3 addObject:dictList3];
}
NSDictionary *dictList2 = [[NSDictionary alloc] initWithObjectsAndKeys:#"Hospitals", #"name", #"1", #"level", array3, #"Objects", nil];
NSMutableArray *array2 = [[NSMutableArray alloc] initWithObjects:dictList2, nil];
for (int i = 0; i < [objects count]; i++) {
if (i == 0) {
dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:[objects objectAtIndex:0], #"name", #"0", #"level", array2, #"Objects", nil];
[array1 addObject:dictionary];
} else if (i == 1) {
dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:[objects objectAtIndex:1], #"name", #"0", #"level", array6, #"Objects", nil];
[array1 addObject:dictionary];
} else if (i == 2) {
dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:[objects objectAtIndex:2], #"name", #"0", #"level", array61, #"Objects", nil];
[array1 addObject:dictionary];
}
// else {
// dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:[objects objectAtIndex:3], #"name", #"0", #"level", array2, #"Objects", nil];
// [array1 addObject:dictionary];
//}
}
dictList = [[NSDictionary alloc] initWithObjectsAndKeys:array1, #"Objects", nil];
NSLog(#"DictList :: %#", dictList);
arrayOriginal = [dictList valueForKey:#"Objects"];
NSLog(#"Array Original :: %#", arrayOriginal);
[arraylist addObjectsFromArray:arrayOriginal];
//[tblist.delegate tableView:tblist didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
//[tblist.delegate tableView:tblist didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
}
#pragma mark - TableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [arraylist count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//static NSString *CellIdentifier = #"CustomCellIdentifier";
NSUInteger IndentLevel = [[[arraylist objectAtIndex:indexPath.row] valueForKey:#"level"] intValue];
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (IndentLevel == 0) {
CustomCellHeader *cell = (CustomCellHeader *)[tableView dequeueReusableCellWithIdentifier:#"CellIdentifier"];
if (cell == nil) {
[[NSBundle mainBundle]loadNibNamed:#"CustomCellHeader" owner:self options:nil];
cell = self.headercell;
self.headercell = nil;
}
cell.lblHeader.text = [[arraylist objectAtIndex:indexPath.row] valueForKey:#"name"];
[cell setIndentationLevel:[[[arraylist objectAtIndex:indexPath.row] valueForKey:#"level"] intValue]];
NSLog(#"indexFor level 0 ::%# %d",cell.lblHeader.text, indexPath.row);
return cell;
} else if (IndentLevel == 1) {
CustomCellSubHeader *cell = (CustomCellSubHeader *)[tableView dequeueReusableCellWithIdentifier:#"CellIdentifier"];
if (!cell) {
[[NSBundle mainBundle]loadNibNamed:#"CustomCellSubHeader" owner:self options:nil];
cell = self.subheadercell;
self.subheadercell = nil;
NSLog(#"dicbtn %#", dictBtnStatus);
}
NSString *strName = [[arraylist objectAtIndex:indexPath.row] valueForKey:#"name"];
NSString *str = [dictBtnStatus objectForKey:strName];
NSLog(#"indexFor level 1 ::%# %d", strName, indexPath.row);
if ([str isEqualToString:#"1"]) {
[cell.btnarrow setImage:[UIImage imageNamed:#"dwn1_arow.png"] forState:UIControlStateNormal];
[cell.imgSubHeader setImage:[UIImage imageNamed:#"tab_active.png"]];
}
// else {
// [cell.imgSubHeader setImage:[UIImage imageNamed:#"tab_default.png"]];
//}
cell.lblSubHeader.text = strName;
[cell setIndentationLevel:[[[arraylist objectAtIndex:indexPath.row] valueForKey:#"level"] intValue]];
if (indexPath.row == arraylist.count - 1) {
cell.imgShadow.hidden = NO;
}
return cell;
} else if (IndentLevel == 2) {
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:#"CellIdentifier"];
if (cell == nil) {
[[NSBundle mainBundle]loadNibNamed:#"CustomCell" owner:self options:nil];
cell = self.cells;
self.cells = nil;
}
cell.txtAddress.text = [[arraylist objectAtIndex:indexPath.row] valueForKey:#"name"];
[cell.btnCall addTarget:self action:#selector(btnCall:) forControlEvents:UIControlEventTouchUpInside];
[cell setIndentationLevel:[[[arraylist objectAtIndex:indexPath.row] valueForKey:#"level"] intValue]];
return cell;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
CustomCellSubHeader *cell;
if ([[tblist cellForRowAtIndexPath:indexPath] isKindOfClass:[CustomCellSubHeader class]]) {
cell = (CustomCellSubHeader*)[tblist cellForRowAtIndexPath:indexPath];
UIImage *img = [cell.btnarrow imageForState:UIControlStateNormal];
if ([img isEqual:[UIImage imageNamed:#"dwn1_arow.png"]]) {
[cell.btnarrow setImage:[UIImage imageNamed:#"gry_arrow.png"] forState:UIControlStateNormal];
[dictBtnStatus setValue:#"0" forKey:cell.lblSubHeader.text];
[cell.imgSubHeader setImage:[UIImage imageNamed:#"tab_default.png"]];
cell.imgShadow.hidden = NO;
} else {
[cell.btnarrow setImage:[UIImage imageNamed:#"dwn1_arow.png"] forState:UIControlStateNormal];
dictBtnStatus = [[NSMutableDictionary alloc] init];
[dictBtnStatus setValue:#"1" forKey:cell.lblSubHeader.text];
[cell.imgSubHeader setImage:[UIImage imageNamed:#"tab_active.png"]];
cell.imgShadow.hidden = YES;
}
}
NSMutableArray *arrIndex = [[NSMutableArray alloc] init];
NSUInteger IndentLevel = [[[arraylist objectAtIndex:indexPath.row] valueForKey:#"level"] intValue];
if (IndentLevel == 0) {
arrLast = [[NSMutableArray alloc] init];
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSDictionary *d = [arraylist objectAtIndex:indexPath.row];
if ([d valueForKey:#"Objects"]) {
NSArray *ar = [d valueForKey:#"Objects"];
BOOL isAlreadyInserted = NO;
for (NSDictionary *dInner in ar) {
NSInteger index = [arraylist indexOfObjectIdenticalTo:dInner];
isAlreadyInserted = (index > 0 && index != NSIntegerMax);
if (isAlreadyInserted) break;
}
if (isAlreadyInserted) {
[self miniMizeThisRows:ar];
} else {
NSUInteger count = indexPath.row + 1;
NSMutableArray *arCells = [NSMutableArray array];
for (NSDictionary *dInner in ar) {
[arCells addObject:[NSIndexPath indexPathForRow:count inSection:0]];
[arrLast addObject:dInner];
[arraylist insertObject:dInner atIndex:count++];
}
[tableView insertRowsAtIndexPaths:arCells withRowAnimation:UITableViewRowAnimationBottom];
}
}
//NSUInteger IndentLevel = [[[arraylist objectAtIndex:indexPath.row] valueForKey:#"level"] intValue];
if (IndentLevel == 0) {
NSMutableIndexSet *discardedItems = [NSMutableIndexSet indexSet];
for (int i = 0 ; i < arraylist.count; i++) {
NSDictionary *dic = [arraylist objectAtIndex:i];
if ([[dic valueForKey:#"level"] intValue] != 0) {
NSInteger index = [arrLast indexOfObjectIdenticalTo:dic];
if ((index >= 0 && index != NSIntegerMax)) {
} else {
[discardedItems addIndex:i];
[arrIndex addObject:[NSIndexPath indexPathForRow:i inSection:0]];
}
}
}
if (discardedItems.count > 0) {
[arraylist removeObjectsAtIndexes:discardedItems];
[tblist deleteRowsAtIndexPaths:arrIndex withRowAnimation:UITableViewRowAnimationNone];
}
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger indentLevel = [[[arraylist objectAtIndex:indexPath.row] valueForKey:#"level"] intValue];
if (indentLevel == 0) {
return 40;
} else if (indentLevel == 1) {
return 25;
} else if (indentLevel == 2) {
CustomCell *cell = ((CustomCell *)[tableView dequeueReusableCellWithIdentifier:#"CellIdentifier"]);
CGSize maximumSize = CGSizeMake(300, 9999);
UIFont *myFont = [UIFont fontWithName:#"Arial" size:11.5];
CGSize myStringSize = [cell.txtAddress.text sizeWithFont:myFont constrainedToSize:maximumSize lineBreakMode:NSLineBreakByWordWrapping];
[cell.txtAddress setFrame:CGRectMake(cell.txtAddress.frame.origin.x, cell.txtAddress.frame.origin.y, cell.txtAddress.frame.size.width, myStringSize.height)];
if (myStringSize.height > 80) {
myStringSize.height = 50;
[cell.txtAddress setFrame:CGRectMake(cell.txtAddress.frame.origin.x, cell.txtAddress.frame.origin.y, cell.txtAddress.frame.size.width, myStringSize.height)];
cell.txtAddress.scrollEnabled = YES;
} else {
cell.txtAddress.scrollEnabled = YES;
myStringSize.height = 40;
}
return myStringSize.height + 50;
} else return 25;
}
#pragma mark - TableAnimation
- (void)miniMizeThisRows:(NSArray *)ar {
for (NSDictionary *dInner in ar) {
NSUInteger indexToRemove = [arraylist indexOfObjectIdenticalTo:dInner];
NSArray *arInner=[dInner valueForKey:#"Objects"];
if (arInner && [arInner count] > 0) {
[self miniMizeThisRows:arInner];
}
if ([arraylist indexOfObjectIdenticalTo:dInner] != NSNotFound) {
[arraylist removeObjectIdenticalTo:dInner];
[tblist deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:indexToRemove inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}
}
}
#pragma mark - Buttons
- (IBAction)btnCall:(id)sender {
UIAlertView *Notpermitted = [[UIAlertView alloc] initWithTitle:#"Alert" message:#"Do you want to call on this number." delegate:nil cancelButtonTitle:#"NO" otherButtonTitles:#"YES", nil];
Notpermitted.delegate = self;
[Notpermitted tag];
[Notpermitted show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 1) {
NSString *strCall = [NSString stringWithFormat:#"tel://999-999-9999"];
NSURL *url = [NSURL URLWithString:strCall];
UIDevice *device = [UIDevice currentDevice];
if ([[device model] isEqualToString:#"iPhone"] ) {
[[UIApplication sharedApplication] openURL:url];
} else {
UIAlertView *Notpermitted = [[UIAlertView alloc] initWithTitle:#"Alert" message:#"Your device doesn't support this feature." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[Notpermitted show];
}
}
}
see following tutorial
http://www.cocoanetics.com/2011/03/expandingcollapsing-tableview-sections/
www.alexandre-gomes.com/?p=482
Expand/collapse section in UITableView in iOS