I am making an application in which I have to read the contacts from an ABAddressBook.
I have read the data and stored it in a dictionary.I want to display the names
alphabetically in every section. Each object in the dictionary refers to the details of a single person. Any help ?
(
{
letter = D;
name = zzzz;
telephone = "1234566";
},
{
letter = R;
name = "ffff";
telephone = "332333";
},
{
letter = A;
name = aaaaa;
telephone = "1112226";
},
{
letter = s;
name = ssssss;
telephone = "234 56792";
},
{
letter = K;
name = "Klll";
telephone = "(888) 888-8888";
}
)
use the following link,
http://developer.apple.com/library/ios/#samplecode/TableViewSuite/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007318
I am sending code, I have done already this type of task. Actually your problem you not able sort dictictionary.
please refer my code for reference.
#import <UIKit/UIKit.h>
#import <AddressBook/AddressBook.h>
#import "AddressBookUI/AddressBookUI.h"
#interface AddressBookViewController : UIViewController<UITableViewDataSource,UITableViewDelegate,ABNewPersonViewControllerDelegate>
{
IBOutlet UITableView* addressNameView;
ABAddressBookRef _addressBook;
}
#property(nonatomic,retain)UITableView* addressNameView;
#property (nonatomic, retain) NSMutableArray *contacts;
#property (nonatomic, retain)IBOutlet UILabel *titleText;
#property(nonatomic,retain)IBOutlet UISegmentedControl *segmentControl;
-(IBAction)backAction:(id)sender;
#end
/****************/
#import "AddressBookViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "AddressEntryDetailController.h"
#import "MenuViewController.h"
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
NSInteger static compareViewsByOrigin(id sp1, id sp2, void *context)
{
// UISegmentedControl segments use UISegment objects (private API). Then we can safely
// cast them to UIView objects.
float v1 = ((UIView *)sp1).frame.origin.x;
float v2 = ((UIView *)sp2).frame.origin.x;
if (v1 < v2)
return NSOrderedAscending;
else if (v1 > v2)
return NSOrderedDescending;
else
return NSOrderedSame;
}
#implementation AddressBookViewController
#synthesize addressNameView,contacts;
#synthesize titleText,segmentControl;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)didChangeSegmentControl:(UISegmentedControl *)control
{
int index=control.selectedSegmentIndex;
NSLog(#"Slected Index : %d",index);
if(index==1)
{
[self getAllContacts];
}
else
{
[self getAllContactsByRelevence];
}
}
-(void)getAllContacts
{
ABRecordRef source = ABAddressBookCopyDefaultSource(_addressBook);
NSArray *tempArray = (NSArray *)(ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(_addressBook, source, kABPersonSortByFirstName));
[contacts removeAllObjects];
if ([tempArray count] > 0)
{
[contacts addObjectsFromArray:tempArray];
}
[addressNameView reloadData];
titleText.text=#"All";
}
-(void)getAllContactsByRelevence
{
ABRecordRef source = ABAddressBookCopyDefaultSource(_addressBook);
NSArray *tempArray = (NSArray *)(ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(_addressBook, source, kABPersonSortByLastName));
[contacts removeAllObjects];
if ([tempArray count] > 0)
{
[contacts addObjectsFromArray:tempArray];
}
[addressNameView reloadData];
titleText.text=#"All";
}
- (void)viewDidLoad
{
_addressBook = ABAddressBookCreate();
contacts=[[NSMutableArray alloc]init];
[self getAllContacts];
addressNameView.layer.borderWidth=2;
addressNameView.layer.cornerRadius=13;
addressNameView.layer.borderColor =[UIColor colorWithRed:192.0f/255.0f green:189.0f/255.0f blue:189.0f/255.0f alpha:1.0f].CGColor;
addressNameView.backgroundColor=[UIColor colorWithRed:236.0f/255.0f green:236.0f/255.0f blue:235.0f/255.0f alpha:1.0f];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
[self CreateAlphabetButton];
self.segmentControl.selectedSegmentIndex=1;
[self.segmentControl addTarget:self action:#selector(didChangeSegmentControl:) forControlEvents:UIControlEventValueChanged];
}
-(void)CreateAlphabetButton
{
int yPoint=110;
NSString *list=#"*ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for(int y=1;y<=27;y++)
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(720,yPoint,50,28);
yPoint+=29;
button.titleLabel.text=[list substringWithRange:NSMakeRange(y-1, 1)];
UILabel *readding=[[UILabel alloc]initWithFrame:CGRectMake(0, 0,40, 30)];
readding.text=[list substringWithRange:NSMakeRange(y-1, 1)];
readding.textColor=[UIColor darkTextColor];
[readding setTextAlignment:UITextAlignmentCenter];
readding.font=[UIFont boldSystemFontOfSize:20.0];
readding.backgroundColor = [UIColor clearColor];
[button addSubview:readding];
[button addTarget:self action:#selector(toggleOpen:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
[self.view bringSubviewToFront:button];
}
}
-(IBAction)toggleOpen:(id)sender
{
UIButton *btn=(UIButton*)sender;
NSLog(#"%#",btn.titleLabel.text);
//for searching
if([btn.titleLabel.text isEqualToString:#"*"])
{
[self getAllContacts];
titleText.text=#"All";
}
else
{
NSArray *tempArray = (NSArray *)(ABAddressBookCopyPeopleWithName(_addressBook,(CFStringRef)btn.titleLabel.text));
[contacts removeAllObjects];
if ([tempArray count] > 0)
{
[contacts addObjectsFromArray:tempArray];
}
[addressNameView reloadData];
titleText.text=btn.titleLabel.text;
}
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
-(IBAction)backAction:(id)sender
{
//MenuViewController *menuView=[[MenuViewController alloc]initWithNibName:#"MenuViewController" bundle:[NSBundle mainBundle]];
//[self presentModalViewController:menuView animated:YES];
[self dismissModalViewControllerAnimated:YES];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return UIInterfaceOrientationIsPortrait(interfaceOrientation);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if([self.contacts count]==0)
return 1;
return [self.contacts count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"TableViewCellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.tag = indexPath.row;
if([self.contacts count]>0)
{
NSObject *object = [self.contacts objectAtIndex:indexPath.row];
NSString *firstName=[(NSString *)ABRecordCopyValue((ABRecordRef)object, kABPersonFirstNameProperty) autorelease];
NSString *lastName =[(NSString *)ABRecordCopyValue((ABRecordRef)object, kABPersonLastNameProperty) autorelease];
if(lastName)
cell.textLabel.text=[NSString stringWithFormat:#"%# %#",firstName,lastName];
else
cell.textLabel.text=firstName;
}
else
{
cell.textLabel.text=#"No Contacts";
}
//UISwipeGestureRecognizer* gestureR;
//gestureR = [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(handleSwipeFrom:)] autorelease];
// gestureR.direction = UISwipeGestureRecognizerDirectionLeft;
// [cell addGestureRecognizer:gestureR];
// cell.editing=YES;
return cell;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)aTableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
if([self.contacts count]>0)
return UITableViewCellEditingStyleDelete;
else
return UITableViewCellEditingStyleNone;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
NSLog(#"Delete Clicked on cell Index : %d",indexPath.row);
// Commit the delete
ABRecordRef* personObject=(ABRecordRef*) [self.contacts objectAtIndex:indexPath.row];
if(ABAddressBookRemoveRecord(_addressBook, personObject, NULL))
{
ABAddressBookSave(_addressBook, NULL);
[self getAllContacts];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert"
message:#"Contact succesfully deleted"
delegate:self cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
}
}
/*
- (void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer
{
NSLog(#"%d = %d",recognizer.direction,recognizer.state);
}
*/
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 54;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if([self.contacts count]>0)
{
AddressEntryDetailController *entryDetail=[[AddressEntryDetailController alloc]initWithNibName:#"AddressEntryDetailController" bundle:[NSBundle mainBundle]];
int index=indexPath.row;
entryDetail.personObject=(ABRecordRef*) [self.contacts objectAtIndex:index];
entryDetail._addressBook=&_addressBook;
entryDetail.addressBookViewController=self;
[self presentModalViewController:entryDetail animated:YES];
}
}
-(IBAction)addToAddressbook:(id)sender
{
ABNewPersonViewController *picker = [[ABNewPersonViewController alloc] init];
picker.newPersonViewDelegate = self;
UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:picker];
[self presentModalViewController:navigation animated:YES];
[picker release];
[navigation release];
/* ABPeoplePickerNavigationController *picker =
[[ABPeoplePickerNavigationController alloc] init];
picker.peoplePickerDelegate = self;
[self presentModalViewController:picker animated:YES];*/
}
#pragma mark ABNewPersonViewControllerDelegate methods
// Dismisses the new-person view controller.
- (void)newPersonViewController:(ABNewPersonViewController *)newPersonViewController didCompleteWithNewPerson:(ABRecordRef)person
{
[self dismissModalViewControllerAnimated:YES];
[self getAllContacts];
}
Related
I met with an requirement in which I had UISearchBar as like follows.
Step : 1 (Initial look of the SearchBar)
Step : 2 (User types string and immediate Search)
Step : 3 (Selecting any of them in the Search List)
Step : 4 (Adding the button on the SearchBar)
Step : 5 (Finally Action on the Button)
This might continue. I mean to say is he can enter the text further more but the functionality should be the same.
Could anyone please help me ? Please, I am in a need.
UPDATE
You can watch this same functionality on your iMac Finder Search
This is what i have tried.
#import "ViewController.h"
#import "customPopOverController.h"
#import <QuartzCore/QuartzCore.h>
#interface ViewController ()
#property (strong, nonatomic) UIView *searchView;
#property (strong, nonatomic) UITableView *sampleView;
#property (strong, nonatomic) NSMutableArray *arrayForListing;
#property (strong, nonatomic) UITextField *txtFieldSearch;
#end
#implementation ViewController
#synthesize searchView = _searchView;
#synthesize customPopOverController = _customPopOverController;
#synthesize txtFieldSearch = _txtFieldSearch;
#synthesize sampleView = _sampleView;
#synthesize arrayForListing = _arrayForListing;
#synthesize btnforExtra = _btnforExtra;
- (void)viewDidLoad
{
[super viewDidLoad];
self.arrayForListing = [[NSMutableArray alloc]init];
[self loadTheSearchView];
[self applyUIStyle];
}
- (void)loadTheSearchView
{
self.searchView = [[UIView alloc]initWithFrame:CGRectMake(20, 100, 280, 44)];
[self.searchView setBackgroundColor:[UIColor whiteColor]];
[self.view addSubview:self.searchView];
[self placeTheTextView];
}
- (void)placeTheTextView
{
self.txtFieldSearch = [[UITextField alloc]initWithFrame:CGRectMake(25, 9, 230, 30)];
[self.txtFieldSearch setDelegate:self];
[self.searchView addSubview:self.txtFieldSearch];
}
- (void)applyUIStyle
{
self.searchView.layer.cornerRadius = 20.0f;
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(textField.text.length!=0)
{
[self.arrayForListing removeAllObjects];
[self.arrayForListing addObject:[NSString stringWithFormat:#"File Contains %#",textField.text]];
[self callThePop];
}
return YES;
}
- (void)callThePop
{
UIViewController *contentViewController = [[UIViewController alloc] init];
contentViewController.contentSizeForViewInPopover = CGSizeMake(self.searchView.frame.size.width, 50);
self.sampleView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, contentViewController.contentSizeForViewInPopover.width, contentViewController.contentSizeForViewInPopover.height)];
[self.sampleView setDelegate:self];
[self.sampleView setDataSource:self];
[self.sampleView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLineEtched];
[self.sampleView setBackgroundColor:[UIColor clearColor]];
[contentViewController.view addSubview:self.sampleView];
self.customPopOverController = [[customPopOverController alloc]initWithContentViewController:contentViewController];
self.customPopOverController.delegate = self;
UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:#selector(callYourMethod:)];
swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
[self.sampleView addGestureRecognizer:swipeRight];
[self.customPopOverController presentPopoverFromRect:self.searchView.frame inView:self.view permittedArrowDirections:(UIPopoverArrowDirectionUp|UIPopoverArrowDirectionDown| UIPopoverArrowDirectionLeft|UIPopoverArrowDirectionRight) animated:YES];
}
- (BOOL)textFieldShouldClear:(UITextField *)textField
{
return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - Table View Delegate Methods
#pragma mark
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.arrayForListing.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifer = #"Cell";
UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifer];
if (cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifer];
}
cell.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[cell.textLabel setTextAlignment:UITextAlignmentCenter];
[cell.textLabel setNumberOfLines:0];
[cell.textLabel setLineBreakMode:UILineBreakModeCharacterWrap];
cell.textLabel.text = [self.arrayForListing objectAtIndex:indexPath.row];
[cell.textLabel setFont:[UIFont fontWithName:#"TrebuchetMS" size:14]];
cell.textLabel.textColor = [UIColor whiteColor];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (self.customPopOverController)
{
[self.customPopOverController dismissPopoverAnimated:YES];
}
UITableViewCell * cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
if (self.txtFieldSearch.text.length == 0)
{
self.txtFieldSearch.text = cell.textLabel.text;
}
else
{
self.btnforExtra = [[UIButton alloc]initWithFrame:CGRectMake(10+(buttonsCount*45), 8, 45, 25)];
[self.btnforExtra setBackgroundColor:[UIColor colorWithRed:0.503 green:0.641 blue:0.794 alpha:1.000]];
[self.btnforExtra setTitle:self.txtFieldSearch.text forState:UIControlStateNormal];
[self.btnforExtra setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[self.btnforExtra.layer setCornerRadius:8.0f];
[self.txtFieldSearch setFrame:CGRectMake(self.btnforExtra.frame.origin.x+self.btnforExtra.frame.size.width+10, 9, 230, 30)];
self.txtFieldSearch.text = #"";
[self.searchView addSubview:self.btnforExtra];
buttonsCount++;
}
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (tableView.editing == UITableViewCellEditingStyleDelete)
{
[tableView beginUpdates];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
[self.arrayForListing removeObjectAtIndex:indexPath.row];
[tableView endUpdates];
}
}
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"IndexPath.row == %i", indexPath.row);
}
#pragma mark - custom PopOver Delegate Methods
#pragma mark
- (BOOL)popoverControllerShouldDismissPopover:(customPopOverController *)thePopoverController
{
return YES;
}
- (void)popoverControllerDidDismissPopover:(customPopOverController *)thePopoverController
{
self.customPopOverController = nil;
}
#end
DISCLAIMER: this solution is deeply flawed, probably in many ways. It's the first solution that I came up with and I've done VERY little optimization on it (aka none).
So, I was bored, and I came up with something that I think fits the bill. Keep in mind that this only does the display of what you're asking about (and it does it somewhat poorly at that), it does not handle the actual search functionality as I'm not sure what you're searching. It also has some static values programmed in (such as file types array, and I dropped the view controller into a UINavigationController and did some static sizes based on that) that you'll want to change. I make use of WYPopoverController, which can be found here: WYPopoverController. Let me know how it works for you- feel free to critique the hell out if it.
ViewController.h
#interface ViewController : UIViewController <UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource>
{
}
ViewController.m
#import "ViewController.h"
#import "WYPopoverController.h"
#import "SearchButton.h"
#import <QuartzCore/QuartzCore.h>
#interface ViewController () <WYPopoverControllerDelegate>
{
UITextField *searchField;
UIView *searchesView;
UIScrollView *scrollView;
WYPopoverController *newSearchController;
WYPopoverController *existingSearchController;
NSMutableArray *buttonsArray;
SearchButton *activeButton;
NSArray *kindsArray;
NSMutableArray *matchedKinds;
// using UITableViewController instead of just UITableView so I can set preferredContentSize on the controller
UITableViewController *searchTable;
UITableViewController *existingTable;
}
#end
#implementation ViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
searchField = [[UITextField alloc] initWithFrame:CGRectMake(20, 75, 280, 30)];
searchField.borderStyle = UITextBorderStyleRoundedRect;
searchField.autocorrectionType = UITextAutocorrectionTypeNo;
searchField.delegate = self;
[self.view addSubview:searchField];
searchesView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, searchField.frame.size.height)];
scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 0, searchField.frame.size.height)];
[scrollView addSubview:searchesView];
searchField.leftView = scrollView;
searchField.leftViewMode = UITextFieldViewModeAlways;
[searchField becomeFirstResponder];
kindsArray = [NSArray arrayWithObjects:#"Audio", #"Video", #"Other", #"Text", nil];
matchedKinds = [[NSMutableArray alloc] init];
buttonsArray = [[NSMutableArray alloc] init];
[searchField addTarget:self
action:#selector(textFieldDidChange:)
forControlEvents:UIControlEventEditingChanged];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Text Field Delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[newSearchController dismissPopoverAnimated:YES completion:^{
[self popoverControllerDidDismissPopover:newSearchController];
}];
return YES;
}
// not technically part of the TF delegate, but it fits better here
- (void)textFieldDidChange:(UITextField *)tf
{
if(tf.text.length > 0)
{
if(newSearchController == nil)
{
searchTable = [[UITableViewController alloc] init];
searchTable.tableView.delegate = self;
searchTable.tableView.dataSource = self;
searchTable.preferredContentSize = CGSizeMake(320, 136);
newSearchController = [[WYPopoverController alloc] initWithContentViewController:searchTable];
newSearchController.delegate = self;
newSearchController.popoverLayoutMargins = UIEdgeInsetsMake(10, 10, 10, 10);
newSearchController.theme.arrowHeight = 5;
searchTable.tableView.tag = 1;
[newSearchController presentPopoverFromRect:searchField.bounds
inView:searchField
permittedArrowDirections:WYPopoverArrowDirectionUp
animated:YES
options:WYPopoverAnimationOptionFadeWithScale];
}
[matchedKinds removeAllObjects];
for(NSString *type in kindsArray)
{
NSRange foundRange = [[type lowercaseString] rangeOfString:[tf.text lowercaseString]];
if(foundRange.location != NSNotFound)
{
// Found a match!
[matchedKinds addObject:type];
}
}
[searchTable.tableView reloadData];
}
else
{
[newSearchController dismissPopoverAnimated:YES completion:^{
[self popoverControllerDidDismissPopover:newSearchController];
}];
}
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if(tableView.tag == 1)
return 2;
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(tableView.tag == 1)
{
if(section == 0)
return 1;
return [matchedKinds count];
}
return 3;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
if(tableView.tag == 1)
{
if(section == 0)
return #"Filenames";
else
return #"Kinds";
}
return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 30.0f;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:#"reuser"];
// Configure the cell...
if(tableView.tag == 1)
{
if(indexPath.section == 0)
{
cell.textLabel.text = [NSString stringWithFormat:#"Name matches: %#", searchField.text];
}
else
{
cell.textLabel.text = [matchedKinds objectAtIndex:indexPath.row];
}
}
else
{
if(indexPath.row == 0)
{
switch (tableView.tag) {
case 2:
cell.textLabel.text = #"Filename";
break;
default:
cell.textLabel.text = #"Kind";
break;
}
}
else if(indexPath.row == 1)
cell.textLabel.text = #"Everything";
else
cell.textLabel.text = #"<Delete>";
}
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(tableView.tag == 1) // new search table tapped
{
SearchButton *searchedButton = [SearchButton buttonWithType:UIButtonTypeSystem];
if(indexPath.section == 0)
{
searchedButton.type = ButtonTypeName;
searchedButton.searchedString = searchField.text;
}
else
{
searchedButton.type = ButtonTypeKind;
searchedButton.searchedString = [matchedKinds objectAtIndex:indexPath.row];
}
searchedButton.defaulted = YES;
searchedButton.titleLabel.font = [UIFont systemFontOfSize:14.0f];
[searchedButton setTitleColor:[UIColor darkTextColor]
forState:UIControlStateNormal];
[searchedButton addTarget:self
action:#selector(buttonTapped:)
forControlEvents:UIControlEventTouchUpInside];
[searchedButton setBackgroundColor:[UIColor colorWithWhite:0.9f alpha:1.0f]];
searchedButton.layer.cornerRadius = 5.0f;
searchedButton.clipsToBounds = YES;
[buttonsArray addObject:searchedButton];
activeButton = searchedButton;
searchField.text = #"";
[self updateButtonsFromCreation:YES];
[newSearchController dismissPopoverAnimated:YES completion:^{
[self popoverControllerDidDismissPopover:newSearchController];
}];
}
else // text field of an existing search
{
switch (indexPath.row) {
case 0:
activeButton.defaulted = YES;
break;
case 1:
activeButton.defaulted = NO;
break;
default:
[buttonsArray removeObject:activeButton];
break;
}
[self updateButtonsFromCreation:NO];
[existingSearchController dismissPopoverAnimated:YES completion:^{
[self popoverControllerDidDismissPopover:existingSearchController];
}];
}
}
#pragma mark - Popover delegate
- (void)popoverControllerDidDismissPopover:(WYPopoverController *)controller
{
if(controller == newSearchController)
{
newSearchController = nil;
}
else
{
existingSearchController = nil;
}
}
#pragma mark - Other functions
- (void)updateButtonsFromCreation:(BOOL)creation
{
[[searchesView subviews] makeObjectsPerformSelector:#selector(removeFromSuperview)];
float widthTotal = 0;
for(SearchButton *button in buttonsArray)
{
NSString *buttonText;
if(button.defaulted)
{
if(button.type == ButtonTypeName)
buttonText = #"Name: ";
else
buttonText = #"Kind: ";
}
else
buttonText = #"Any: ";
buttonText = [buttonText stringByAppendingString:button.searchedString];
[button setTitle:buttonText forState:UIControlStateNormal];
CGSize buttonSize = [buttonText sizeWithAttributes:#{NSFontAttributeName:[UIFont systemFontOfSize:14.0f]}];
button.frame = CGRectMake(widthTotal + 2, 2, buttonSize.width + 4, searchField.frame.size.height - 4);
widthTotal += button.frame.size.width + 2;
[searchesView addSubview:button];
}
searchesView.frame = CGRectMake(0, 0, widthTotal, searchesView.frame.size.height);
scrollView.frame = CGRectMake(0, 0, ((widthTotal > 200) ? 200 : widthTotal), scrollView.frame.size.height);
scrollView.contentSize = CGSizeMake(widthTotal, scrollView.frame.size.height);
if(creation)
{
scrollView.contentOffset = CGPointMake(activeButton.frame.origin.x, 0);
}
}
- (void)buttonTapped:(SearchButton *)sender
{
activeButton = sender;
existingTable = [[UITableViewController alloc] init];
existingTable.tableView.delegate = self;
existingTable.tableView.dataSource = self;
existingTable.preferredContentSize = CGSizeMake(160, 90);
existingSearchController = [[WYPopoverController alloc] initWithContentViewController:existingTable];
existingSearchController.delegate = self;
existingSearchController.popoverLayoutMargins = UIEdgeInsetsMake(10, 10, 10, 10);
existingSearchController.theme.arrowHeight = 5;
existingTable.tableView.tag = sender.type;
[existingSearchController presentPopoverFromRect:sender.frame
inView:scrollView
permittedArrowDirections:WYPopoverArrowDirectionUp
animated:YES
options:WYPopoverAnimationOptionFadeWithScale];
}
#end
SearchButton.h
typedef enum {ButtonTypeName = 2,
ButtonTypeKind = 3} ButtonType;
#interface SearchButton : UIButton
#property (nonatomic) ButtonType type;
#property (nonatomic) BOOL defaulted;
#property (nonatomic, retain) NSString *searchedString;
#end
SearchButton.m
no changes to default generated
I have a table view with custom cells ,there are uibuttons on custom cell ,if i select button except that cell remaining all cells should be grayouted or disabled is it possible.
// code in tableview class
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
NSLog(#"No OF rows:%d",[contents count]);
return [contents count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
static NSString *cellIdentifier = #"cell";
// Try to retrieve from the table view a now-unused cell with the given identifier.
cell = (uploadCustomCell *)[tableView dequeueReusableCellWithIdentifier:#"uploadCustomCell"];
if (cell == nil) {
NSLog(#"cell allocated");
// Use the default cell style.
cell = [[uploadCustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"uploadCustomCell"];
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"uploadCustomCell"
owner:self options:nil];
cell = [nib objectAtIndex:0];
}
saveBtnCcell.hidden = YES;
cell.textNamefield.hidden = YES;
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
[cell.defaultSwitch setEnabled:NO];
dictionaryContents = [contents objectAtIndex:indexPath.row];
NSLog(#"dict dict :%#",dictionaryContents);
//
cell
.nameLabelCell.text = [dictionaryContents valueForKey:#"VideoName"];
cell.userName.text = [dictionaryContents valueForKey:#"User"];
NSLog(#"Array Image:%#",arrayimage);
cell.thumbImg.image = [arrayimage objectAtIndex:indexPath.row];
NSLog(#"ARimage:%#,index%d",[arrayimage objectAtIndex:indexPath.row],indexPath.row);
NSString *defaultVideo = [dictionaryContents valueForKey:#"DefaultVideo"];
NSLog(#"Default Video:%#",defaultVideo);
if ([defaultVideo isEqual: #"1"]) {
// [cell.defaultSwitch setOn:YES animated:YES];
[defaultSwitche setOn:YES animated:YES];
}
else{
// [cell.defaultSwitch setOn:NO animated:YES];
[defaultSwitche setOn:NO animated:YES];
}
[cell.defaultSwitch addTarget:self action:#selector(setState:) forControlEvents:UIControlEventValueChanged];
VideoNameTextField.hidden = YES;
return cell;
}
// Code in customcell
#interface uploadCustomCell (){
UploadAllViewController *uploadAll;
}
#end
#implementation uploadCustomCell
#synthesize textNamefield;
#synthesize savebtn,edit,nameLabelCell,textLabel,uploadBTN;
#synthesize defaultSwitch;
//#synthesize uploadAll;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)dealloc {
[_userName release];
[_thumbImg release];
//[savebtn release];
[textNamefield release];
[nameLabelCell release];
[_test release];
[savebtn release];
[defaultSwitch release];
[uploadBTN release];
[super dealloc];
}
- (IBAction)editAction:(id)sender {
[uploadBTN setEnabled:NO];
uploadAll = [[UploadAllViewController alloc]init];
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:uploadAll.tabelView1];
NSIndexPath *indexPath = [uploadAll.tabelView1 indexPathForRowAtPoint:buttonPosition];
int no = indexPath.row;
NSLog(#"index path :%d",no);
[uploadAll didEditButtonPressed:self];
}
- (IBAction)saveBtnAction:(id)sender {
[uploadBTN setEnabled:YES];
[uploadAll didSaveButtonPressed:self];
}
when i select this editAction: except that cell remaining cells should be grayouted.
In your cellForRowAtIndexPath you have to account for the state of your table view, i.e. if one or zero cells are selected. Use that to change the appearance of your cell as you wish. In the example below I have assumed you are having a straight array without any sections, but the same principle would work with indexPaths as well. I use an int selectedRow set to -1 if there is no cell selected.
#define kNoCellSelected -1
// in cellForRowAtIndexPath:
if (self.selectedRow == kNoCellSelected) {
cell.backgroundView.backgroundColor = normalColor;
cell.userInteractionEnabled = YES;
}
else if (self.selectedRow != indexPath.row) {
cell.backgroundView.backgroundColor = disabledColor;
cell.userInteractionEnabled = NO;
}
Don't forget to set selectedRow in didSelectRowAtIndexPath: and in viewDidLoad.
RootViewController.h
#import <UIKit/UIKit.h>
#interface RootViewController : UITableViewController {
NSMutableArray *petsArray;
}
#property (nonatomic, strong) NSMutableArray *petsArray;
#end
RootViewController.m
#import "RootViewController.h"
#import "PetsViewController.h"
#interface RootViewController ()
#end
#implementation RootViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
petsArray = [[NSMutableArray alloc] init];
[petsArray addObject:#"Dog"];
[petsArray addObject:#"Cat"];
[petsArray addObject:#"Snake"];
[self setTitle:#"PETS !"];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [petsArray count];
}
- (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...
cell.textLabel.text = [petsArray objectAtIndex:indexPath.row];
return cell;
}
#pragma mark - Table view delegate
I think that the problem is in didSelectRowAtIndexPath which I can't use in storyboarded project.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
PetsViewController *pets = [[PetsViewController alloc] initWithNibName:#"PetsViewController" bundle:nil];
if ([[petsArray objectAtIndex:indexPath.row] isEqual:#"Dog"]) {
pets.petsInt = 0;
[pets setTitle:[petsArray objectAtIndex:indexPath.row]];
}
if ([[petsArray objectAtIndex:indexPath.row] isEqual:#"Cat"]) {
pets.petsInt = 1;
[pets setTitle:[petsArray objectAtIndex:indexPath.row]];
}
if ([[petsArray objectAtIndex:indexPath.row] isEqual:#"Snake"]) {
pets.petsInt = 2;
[pets setTitle:[petsArray objectAtIndex:indexPath.row]];
}
[self.navigationController pushViewController:pets animated:YES];
}
#end
PetsViewController.h
#import <UIKit/UIKit.h>
#interface PetsViewController : UITableViewController {
NSMutableArray *dogArray;
NSMutableArray *catArray;
NSMutableArray *snakeArray;
int petsInt;
}
#property int petsInt;
#end
PetsViewController.m
#import "PetsViewController.h"
#interface PetsViewController ()
#end
#implementation PetsViewController
#synthesize petsInt;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
dogArray = [[NSMutableArray alloc] initWithObjects:#"HAF",#"hafo", #"hafinio", nil];
catArray = [[NSMutableArray alloc] initWithObjects:#"MYAU",#"myainio", #"mya lya lya", nil];
snakeArray = [[NSMutableArray alloc] initWithObjects:#"fshhhhh",#"fsssss", #"xrt", nil];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
if (petsInt == 0) return [dogArray count];
if (petsInt == 1) return [catArray count];
if (petsInt == 2) return [snakeArray count];
[self.tableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"PetsCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
if (petsInt == 0) cell.textLabel.text = [dogArray objectAtIndex:indexPath.row];
if (petsInt == 1) cell.textLabel.text = [catArray objectAtIndex:indexPath.row];
if (petsInt == 2) cell.textLabel.text = [snakeArray objectAtIndex:indexPath.row];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:#"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
*/
}
#end
[self performSegueWithIdentifier:#"SEGUE_NAME" sender:self];
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"SEGUE_NAME"]) {
PetsViewController *pets = [segue destinationViewController];
[pets setPetsInt:0];
[pets setTitle:#"Title"];
}
}
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
NSIndexPath *indexPath = self.tableView.indexPathForSelectedRow;
if ([[gazel objectAtIndex:indexPath.row] isEqual:#"<էրեբունի> Օդանավակայան"]) {
KangarList *kang = [segue destinationViewController];
kang.kangarInt = 0;
[kang setTitle:[gazel objectAtIndex:indexPath.row]];
}
if ([[gazel objectAtIndex:indexPath.row] isEqual:#"<էրեբունի> Օդանավակայան"]) {
KangarList *kang = [segue destinationViewController];
kang.kangarInt = 1;
[kang setTitle:[gazel objectAtIndex:indexPath.row]];
}
if ([[gazel objectAtIndex:indexPath.row] isEqual:#"<էրեբունի> Օդանավակայան"]) {
KangarList *kang = [segue destinationViewController];
kang.kangarInt = 2;
[kang setTitle:[gazel objectAtIndex:indexPath.row]];
}
if ([[gazel objectAtIndex:indexPath.row] isEqual:#"<էրեբունի> Օդանավակայան"]) {
KangarList *kang = [segue destinationViewController];
kang.kangarInt = 3;
[kang setTitle:[gazel objectAtIndex:indexPath.row]];
}
}
i have tried many ways and i finaly realized the right method, but it works only when under view did load method objects have only one description but if it hase something like thise
gazel = [[NSMutableArray alloc] init];
Data *data = [[Data alloc] init];
data.title = #"<էրեբունի> Օդանավակայան";
data.subtitle = #"Հարաֆ Արևմտյան Թաղամաս";
data.photo = 1;
[gazel addObject:data];
its not working
I have two views, the first (view A) is a table view. Every row has a disclosure button, when I click on the button I display the second view (view B) which is a table view too. When i click on a row, I want to pass the data to view A and display it as detailTextLabel.
#import <UIKit/UIKit.h>
#interface A : UIViewController <UITableViewDelegate, UITableViewDataSource> {
NSDictionary *listData;
NSArray *keys;
}
#property (nonatomic, retain) NSDictionary *listData;
#property (nonatomic, retain) NSArray *keys;
#end
#import "A.h"
#implementation A
#synthesize listData;
#synthesize keys;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)dealloc
{
[listData release];
[keys release];
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"Criteres" ofType:#"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
self.listData = dict;
[dict release];
NSArray *array = [[listData allKeys]sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
self.keys = array;
[super viewDidLoad];
}
- (void)viewDidUnload
{
self.listData = nil;
self.keys = nil;
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark -
#pragma mark Table View Data Source Methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [keys count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSString *key = [keys objectAtIndex:section];
NSArray *nameSection = [listData objectForKey:key];
return [nameSection count];
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSString *key = [keys objectAtIndex:section];
return key;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
NSString *key = [keys objectAtIndex:section];
NSArray *nameSection = [listData objectForKey:key];
static NSString *SectionsTableIdentifier = #"SectionsTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SectionsTableIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:SectionsTableIdentifier] autorelease];
}
cell.textLabel.text = [nameSection objectAtIndex:row];
if (section == 0) {
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
if (row == 2)
cell.detailTextLabel.text = #"En m2";
if (row == 1)
cell.detailTextLabel.text = #"En €";
}
if (section == 1) {
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
}
}
return cell;
}
#pragma mark -
#pragma mark Table Delegate Methods
- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger row = 2;
return row;
}
-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
return indexPath;
}
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *ownerCell = [tableView cellForRowAtIndexPath:indexPath];
if ([ownerCell.textLabel.text isEqualToString:#"Ecole"]) {
B *prixview = [[B alloc]init];
[self.navigationController pushViewController:prixview animated:YES];
prixview.title = #"prix";
}
if ([ownerCell.textLabel.text isEqualToString:#"Crèche"]) {
B *prixview = [[B alloc]init];
[self.navigationController pushViewController:prixview animated:YES];
prixview.title = #"Prix";
}
}
#end
#import <UIKit/UIKit.h>
#interface B : UIViewController <UITableViewDelegate, UITableViewDataSource> {
NSArray *typetab;
NSInteger radioSelectionTypeBien;
NSString *radioSelectionTypeBienString;
}
#property (nonatomic, retain) NSArray *typetab;
#property (nonatomic, retain) NSString *radioSelectionTypeBienString;
#end
#import "B.h"
#implementation B
#synthesize typetab;
#synthesize radioSelectionTypeBienString;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)dealloc
{
[self.radioSelectionTypeBienString release];
[self.typetab release];
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
initWithTitle:#"Critères"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(backButtonActionTypeBien:)];
self.navigationItem.leftBarButtonItem = backButton;
[backButton release];
radioSelectionTypeBien = -1;
NSArray *type = [[NSArray alloc]initWithObjects:#"Appartement",#"Maison",#"Commerce", nil ];
self.typetab = type;
[type release];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
-(IBAction)backButtonActionTypeBien: (id)sender
{
[self.navigationController pushViewController:self.navigationController.parentViewController animated:YES];
}
- (void)viewDidUnload
{
self.radioSelectionTypeBienString = nil;
self.typetab = nil;
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark -
#pragma mark Table View Data Source Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.typetab count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *SimpleTableIdentifier = #"SimpleTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
if (cell == nil) { cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier] autorelease];
}
cell.accessoryType = UITableViewCellAccessoryNone;
cell.textLabel.text = [typetab objectAtIndex:indexPath.row];
if (indexPath.row == radioSelectionTypeBien){
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
radioSelectionTypeBien = indexPath.row;
radioSelectionTypeBienString = [tableView cellForRowAtIndexPath:indexPath].textLabel.text;
[tableView reloadData];
}
#end
Usually i write a method in the controller B like:
-(voi)initVCwithString:(NSString*)_string andSomeObject:(NSObject *)_obj;
(so the controller B must have 2 ivar, a string and an object, that you have to set in this method)
then call this in your didSelectRowAtIndexPath: from the controller A
...
B _vcB=//alloc..init..etc
[_vcB initVCwithString:yourCell.textLabel.text andSomeObject:someObj];
[self.navigationController pushViewController:_vcB animated:YES];
[_vcB release];
Then in cellForRowAtIndexPath of B set cell.detailTextLabel.text=yourStringIvar;
Hope this helps.
Basically there are two possibilities that seems to be suitable. You can write a custom delegate method which pass the value to the A controller, or you can make a notification via notification centre, which can then assign the value to the A controller by catching the notification which will be triggered by picking a cell in the controller B.
I create a table with two sections. Each section has four cells.I want to push to a new view by navigation controller when a certain cell is pressed by user.
However there are two sections. I don't know how to distinguish the cell selected belongs to which section in
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
Please give me some tips. Thank you very much.
Here's my TableViewController.m
#import "TableViewController.h"
#import "LondonController.h"
#import "NewYorkViewController.h"
#import "ParisViewController.h"
#import "TokyoViewController.h"
#implementation TableViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)dealloc
{
[super dealloc];
[tableDataSource release];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
UITableView *table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 460) style:UITableViewStyleGrouped];
[table setDataSource:self];
[table setDelegate:self];
tableDataSource = [[NSMutableArray alloc]init];
NSMutableArray* sec1 = [[NSMutableArray alloc] init];
[sec1 addObject:#"London"];
[sec1 addObject:#"New York"];
[sec1 addObject:#"Paris"];
[sec1 addObject:#"Tokyo"];
[tableDataSource addObject:sec1];
[sec1 release];
NSMutableArray* sec2 = [[NSMutableArray alloc] init];
[sec2 addObject:#"Elton John"];
[sec2 addObject:#"Michael Jackson"];
[sec2 addObject:#"Little Prince"];
[sec2 addObject:#"SMAP"];
[tableDataSource addObject:sec2];
[sec2 release];
[self.view addSubview:table];
[table release];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if ( tableDataSource == nil )
return 1;
return [tableDataSource count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger bucketCount = -1;
NSObject *target_section;
if ( tableDataSource == nil )
return 0;
if( ( bucketCount = [tableDataSource count] ) < 1 || bucketCount <= section || (target_section = [tableDataSource objectAtIndex:section ]) == nil )
return 0;
return [ (NSMutableArray*)target_section count ];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: [NSString stringWithFormat:#"Cell %i",indexPath.section]];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:[NSString stringWithFormat:#"Cell %i",indexPath.section]] autorelease];
}
cell.textLabel.text = (NSString*)[ (NSMutableArray*)[tableDataSource objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
if(section == 0)
{
return #"City";
}
else if(section == 1)
{
return #"Person";
}
else
{
return #"Nothing;
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == 0)
{
LondonViewController *londonViewController = [[LondonViewController alloc] initWithNibName:#"LondonViewController" bundle:nil];
taipeiViewController.title = #"London Info";
[self.navigationController pushViewController:londonViewController animated:YES];
[londonViewController release];
}
else if (indexPath.row == 1)
{
NewYorkViewController *newYorkViewController = [[NewYorkViewController alloc] initWithNibName:#"NewYorkViewController" bundle:nil];
newYorkViewController.title = #"New York Info";
[self.navigationController pushViewController:newYorkViewController animated:YES];
[newYorkViewController release];
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#end
In
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
you should check indexPath.section value to determine the section of the selected cell.
refer a NSIndexpath reference: http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSIndexPath_Class/Reference/Reference.html
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger section = indexPath.section;
NSUInteger row = indexPath.row;
if (section == 0)
{
LondonViewController *londonViewController = [[LondonViewController alloc] initWithNibName:#"LondonViewController" bundle:nil];
taipeiViewController.title = #"London Info";
[self.navigationController pushViewController:londonViewController animated:YES];
[londonViewController release];
}
else if (section == 1)
{
NewYorkViewController *newYorkViewController = [[NewYorkViewController alloc] initWithNibName:#"NewYorkViewController" bundle:nil];
newYorkViewController.title = #"New York Info";
[self.navigationController pushViewController:newYorkViewController animated:YES];
[newYorkViewController release];
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}