UISearchBar same as like iMac Finder Search Functionality - iphone

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

Related

How to expand and collapse rows using header section in a UITableView

I have a table view. Now I want to collapse and expand rows by tapping on the section header. In other words, when I tap the header the rows display for that section. How can I do this?
I draft up some code to give you the idea. The concept is we keep track of collapsed section in NSMutableSet and add/remove it according to the user touch on the section. The collapse/expand animation is actually the animation of adding/removing cells.
#import "ViewController.h"
#interface ViewController () < UITableViewDataSource, UITableViewDelegate> {
NSMutableSet* _collapsedSections;
}
#property (nonatomic, weak) IBOutlet UITableView* tableView;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_collapsedSections = [NSMutableSet new];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 3;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_collapsedSections containsObject:#(section)] ? 0 : 10;
}
-(NSArray*) indexPathsForSection:(int)section withNumberOfRows:(int)numberOfRows {
NSMutableArray* indexPaths = [NSMutableArray new];
for (int i = 0; i < numberOfRows; i++) {
NSIndexPath* indexPath = [NSIndexPath indexPathForRow:i inSection:section];
[indexPaths addObject:indexPath];
}
return indexPaths;
}
-(void)sectionButtonTouchUpInside:(UIButton*)sender {
sender.backgroundColor = [UIColor greenColor];
[self.tableView beginUpdates];
int section = sender.tag;
bool shouldCollapse = ![_collapsedSections containsObject:#(section)];
if (shouldCollapse) {
int numOfRows = [self.tableView numberOfRowsInSection:section];
NSArray* indexPaths = [self indexPathsForSection:section withNumberOfRows:numOfRows];
[self.tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationTop];
[_collapsedSections addObject:#(section)];
}
else {
int numOfRows = 10;
NSArray* indexPaths = [self indexPathsForSection:section withNumberOfRows:numOfRows];
[self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationTop];
[_collapsedSections removeObject:#(section)];
}
[self.tableView endUpdates];
//[_tableView reloadData];
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIButton* result = [UIButton buttonWithType:UIButtonTypeCustom];
[result addTarget:self action:#selector(sectionButtonTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
result.backgroundColor = [UIColor blueColor];
[result setTitle:[NSString stringWithFormat:#"Section %d", section] forState:UIControlStateNormal];
result.tag = section;
return result;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell* result = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
result.textLabel.text = [NSString stringWithFormat:#"Cell %d", indexPath.row];
return result;
}
#end
As already this is a old question now.Me too also searched and in the last got 1 sample code from Github.So I thought of sharing the link,if in near future any one comes up with the same issues.
https://github.com/iSofTom/STCollapseTableView
TLIndexPathTools does this with only a few lines of code on your part. Try running the Collapse sample project. It subclasses TLCollapsibleTableViewController, which has a couple of nice options. It supports expanding a single section at a time or multiple sections. It also optimizes the scroll position when you expand a section to show as many rows of the section as possible. So if you tap on a section near the bottom of the screen, it will scroll up automatically.
The full view controller code of the sample project is as follows:
#import "TLCollapsibleTableViewController.h"
#interface CollapseTableViewController : TLCollapsibleTableViewController
- (IBAction)toggleSingleSectionExpanded:(UISwitch *)sender;
#end
#import "CollapseTableViewController.h"
#import "TLIndexPathSectionInfo.h"
#import "TLCollapsibleDataModel.h"
#define SECTION1_NAME #"Section 1"
#define SECTION2_NAME #"Section 2"
#interface CollapseTableViewController ()
#property (strong, nonatomic) TLIndexPathDataModel *backingDataModel;
#end
#implementation CollapseTableViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//define items for two sections
NSArray *section1Items = #[
#"Fredricksburg",
#"George Washington",
#"Grand Canyon"];
NSArray *section2Items = #[
#"Jelly Bean",
#"Bibliography",
#"Keyboard Shortcut",
#"Metadata",
#"Fundamental",
#"Cellar Door"];
//We're using plain string items, so we don't have a sectionNameKeyPath property
//to use, so instead we explicitly create section info objects
TLIndexPathSectionInfo *section1 = [[TLIndexPathSectionInfo alloc] initWithItems:section1Items andName:SECTION1_NAME];
TLIndexPathSectionInfo *section2 = [[TLIndexPathSectionInfo alloc] initWithItems:section2Items andName:SECTION2_NAME];
//create the backing model, which contains all sections and items
self.backingDataModel = [[TLIndexPathDataModel alloc] initWithSectionInfos:#[section1, section2]
andIdentifierKeyPath:nil andCellIdentifierKeyPath:nil];
[self collapseAll];
}
- (void)tableView:(UITableView *)tableView configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
NSString *item = [self.dataModel itemAtIndexPath:indexPath];
cell.textLabel.text = item;
}
- (IBAction)toggleSingleSectionExpanded:(UISwitch *)sender {
self.singleExpandedSection = sender.isOn;
[self collapseAll];
}
- (void)collapseAll
{
self.dataModel = [[TLCollapsibleDataModel alloc] initWithBackingDataModel:self.backingDataModel
collapsedSectionNames:[NSSet setWithArray:self.backingDataModel.sectionNames]];
}
#end
configure viewForHeaderInSection:
like this
(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
UILabel *lblHeader = [[UILabel alloc]init];
lblHeader.text = #"Section 0";
lblHeader.backgroundColor = [UIColor blueColor];
lblHeader.font = [UIFont fontWithName:#"Avenir" size:18];
lblHeader.textAlignment=NSTextAlignmentLeft;
lblHeader.userInteractionEnabled=YES;
UIGestureRecognizer *gr;
if(section==0){
lblHeader.text = #"Section 0";
gr = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleGesture:)];
}else if(section == 1){
lblHeader.text = #"Section 1";
gr = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleGesture1:)];
}
[lblHeader addGestureRecognizer:gr];
return lblHeader;
}
then write seperate action calls
- (void)handleGesture:(UIGestureRecognizer *)gestureRecognizer {
}
- (void)handleGesture1:(UIGestureRecognizer *)gestureRecognizer {
}

Get value from detailTextLabel after PickerInputViewCell

I have a Custom cell that shows a pickerView when you select a row.
Then you change the value and put it on detailTextLabel.
But this method get the value before it changes.
//Custom Cell
SimplePickerInputTableViewCell *cell = (SimplePickerInputTableViewCell *) [_tableView dequeueReusableCellWithIdentifier:cellIndentifier2];
if (!cell) {
cell = [[SimplePickerInputTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIndentifier2];
UIImageView *lineView2 = [[UIImageView alloc] initWithFrame:CGRectMake(-2, 45, 320, 10)];
lineView2.image = [UIImage imageNamed:#"linha_horizontal.png"];
[cell addSubview:lineView2];
_opcaoTitle = [[UILabel alloc] initWithFrame:CGRectMake(10, 15, 200, 20)];
_opcaoTitle.textAlignment = UITextAlignmentLeft;
_opcaoTitle.textColor = [UIColor blackColor];
_opcaoTitle.text = #"Pista - Feminino";
[cell addSubview:_opcaoTitle];
_opcaoValueF = [[UILabel alloc] initWithFrame:CGRectMake(180, 15, 100, 20)];
_opcaoValueF.textColor = [UIColor blackColor];
[cell addSubview:_opcaoValueF];
}
_opcaoValueF.text = [NSString stringWithFormat:#"R$ %#,00", _eventFemininoValue];
cell.selectionStyle = UITableViewCellSelectionStyleGray;
[cell setValue:#"0"];
return cell;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[_tableView deselectRowAtIndexPath:indexPath animated:YES];
NSString *s = [[[tableView cellForRowAtIndexPath:indexPath] detailTextLabel] text];
NSLog(#"String is: %#", s);
int i = [s intValue];
NSLog(#"This is the int value: %d", i);
}
SimplePicker.m
#import "SimplePickerInputTableViewCell.h"
#implementation SimplePickerInputTableViewCell
#synthesize delegate;
#synthesize value;
__strong NSArray *values = nil;
+ (void)initialize {
values = [NSArray arrayWithObjects:#"0", #"1", #"2", #"3", #"4", #"5", #"6", #"7", #"8", #"9", #"10", nil];
}
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
self.picker.delegate = self;
self.picker.dataSource = self;
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
// Initialization code
self.picker.delegate = self;
self.picker.dataSource = self;
}
return self;
}
- (void)setValue:(NSString *)v {
value = v;
self.detailTextLabel.text = value;
self.detailTextLabel.textColor = [UIColor whiteColor];
self.detailTextLabel.backgroundColor = [UIColor clearColor];
if (![value isEqualToString:#"0"]) {
[self.picker selectRow:[values indexOfObject:value] inComponent:0 animated:YES];
}
_backgroundValue = [[UIImageView alloc] initWithFrame:CGRectMake(285, 3, 40, 40)];
_backgroundValue.image = [UIImage imageNamed:#"home_icon_popular.png"];
[self addSubview:_backgroundValue];
[self sendSubviewToBack:_backgroundValue];
}
#pragma mark -
#pragma mark UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
return [values count];
}
#pragma mark -
#pragma mark UIPickerViewDelegate
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [values objectAtIndex:row];
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
return 44.0f;
}
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
return 300.0f; //pickerView.bounds.size.width - 20.0f;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
self.value = [values objectAtIndex:row];
if (delegate && [delegate respondsToSelector:#selector(tableViewCell:didEndEditingWithValue:)]) {
[delegate tableViewCell:self didEndEditingWithValue:self.value];
}
}
The problem is that you are getting the value as soon as the new cell is created (the cell is probably not even drawn on the screen at this time). To solve this you should capture the value when the use dismisses the picker view.
From the additional code you provided
1) Set up a delegate for the table view cell:
cell.delegate = self;
You can do this right after you create it
2) Add an implementation of tableViewCell:didEndEditingWithValue:
- (void)tableViewCell:(UITableViewCell*)cell didEndEditingWithValue:(NSValue*)value
{
NSLog(#"Value is %#", value);
}

UITableview Data

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

tableviewcell having textfield now i wanted to get textfileld data to be stored in database

My UITableViewCell has UITextField inside, now I want to get UITextField data to be stored in database (using insert command) but how can I be able to access the UITableViewCell's UITextField data
#interface ELCTextfieldCell : UITableViewCell <UITextFieldDelegate> {
id delegate;
UILabel *leftLabel;
UITextField *rightTextField;
NSIndexPath *indexPath;
}
#implementation ELCTextfieldCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) {
leftLabel = [[UILabel alloc] initWithFrame:CGRectZero];
[leftLabel setBackgroundColor:[UIColor clearColor]];
[leftLabel setTextColor:[UIColor colorWithRed:.285 green:.376 blue:.541 alpha:1]];
[leftLabel setFont:[UIFont fontWithName:#"Helvetica" size:12]];
[leftLabel setTextAlignment:UITextAlignmentRight];
[leftLabel setText:#"Left Field"];
[self addSubview:leftLabel];
rightTextField = [[UITextField alloc] initWithFrame:CGRectZero];
rightTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
[rightTextField setDelegate:self];
[rightTextField setPlaceholder:#"Right Field"];
[rightTextField setFont:[UIFont systemFontOfSize:17]];
// FOR MWF USE DONE
[rightTextField setReturnKeyType:UIReturnKeyDone];
[self addSubview:rightTextField];
}
return self;
}
//Layout our fields in case of a layoutchange (fix for iPad doing strange things with margins if width is > 400)
- (void)layoutSubviews {
[super layoutSubviews];
CGRect origFrame = self.contentView.frame;
if (leftLabel.text != nil) {
leftLabel.frame = CGRectMake(origFrame.origin.x, origFrame.origin.y, 90, origFrame.size.height-1);
rightTextField.frame = CGRectMake(origFrame.origin.x+105, origFrame.origin.y, origFrame.size.width-120, origFrame.size.height-1);
} else {
leftLabel.hidden = YES;
NSInteger imageWidth = 0;
if (self.imageView.image != nil) {
imageWidth = self.imageView.image.size.width + 5;
}
rightTextField.frame = CGRectMake(origFrame.origin.x+imageWidth+10, origFrame.origin.y, origFrame.size.width-imageWidth-20, origFrame.size.height-1);
}
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if([delegate respondsToSelector:#selector(textFieldDidReturnWithIndexPath:)]) {
[delegate performSelector:#selector(textFieldDidReturnWithIndexPath:) withObject:indexPath];
}
return YES;
}
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *textString = self.rightTextField.text;
if (range.length > 0) {
textString = [textString stringByReplacingCharactersInRange:range withString:#""];
}
else {
if(range.location == [textString length]) {
textString = [textString stringByAppendingString:string];
}
else {
textString = [textString stringByReplacingCharactersInRange:range withString:string];
}
}
if([delegate respondsToSelector:#selector(updateTextLabelAtIndexPath:string:)]) {
[delegate performSelector:#selector(updateTextLabelAtIndexPath:string:) withObject:indexPath withObject:textString];
}
return YES;
}
#interface RootViewController : UITableViewController <ELCTextFieldDelegate> {
NSArray *labels;
NSArray *placeholders;
}
#implementation RootViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.labels = [NSArray arrayWithObjects:#"First Name",
#"Last Name",
#"Email",
#"Phone Number",
nil];
self.placeholders = [NSArray arrayWithObjects:#"Enter First Name",
#"Enter Last Name",
#"Enter Email",
#"Phone Number (Optional)",
nil];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
ELCTextfieldCell *cell = (ELCTextfieldCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[ELCTextfieldCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
Try setting tag value to the textField and then retrieve the values.
Ex: rightTextField.tag = 1000; // don't use 0
Access the textField using,
UITextField *textField = (UITextField *)[self.view viewWithTag:1000];

Delegate methods of UITableView are not responding

I am quite new to IOS development, so forgive me if this problem turns out to be trivial. The following is the case:
I want to be able to call the didSelectRowAtIndexPath method to trigger some action when a user interacts with a table view cell. However, it seems that this method is never called for some reason. I am fairly certain that my code is valid. I set the delegate and dataSource properties and I conform to the UITableViewDelegate and UITableViewDataSource protocols.
If someone could shed some light on this, I would be very grateful.
My code:
#import <UIKit/UIKit.h>
#import <MessageUI/MessageUI.h>
#class Employee;
#define kTelephoneRowIndex 0
#define kEmailRowIndex 1
#define kLeftLabelTag 4096
#define kRightLabelTag 4097
#interface PersonnelDetailsViewController : UIViewController <UITableViewDelegate,
UITableViewDataSource, MFMailComposeViewControllerDelegate> {
UITableView *contactDetailsTable;
Employee *employee;
}
#property (nonatomic, retain) UITableView *contactDetailsTable;
#property (nonatomic, retain) Employee *employee;
+ (NSString *)resourceFilePath:(NSString *)fileName ofType:(NSString *)type;
#end
and my .m file
#import <QuartzCore/QuartzCore.h>
#import "PersonnelDetailsViewController.h"
#import "Employee.h"
#implementation PersonnelDetailsViewController
#synthesize contactDetailsTable, employee;
+ (NSString *)resourceFilePath:(NSString *)fileName ofType:(NSString *)type {
return [[NSBundle mainBundle] pathForResource:fileName ofType:type];
}
- (void)loadView {
[super loadView];
// Create the header view for the table view
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 110)];
// Set the image, using rounded corners
UIImage *employeeImage;
if ([employee.image length] == 0)
employeeImage = [UIImage imageNamed:#"logoL1nda70by80"];
else
employeeImage = [UIImage imageNamed:employee.image];
UIImageView *employeeImageView = [[UIImageView alloc] initWithImage:employeeImage];
employeeImageView.frame = CGRectMake(10, 15, 70, 80);
employeeImageView.layer.masksToBounds = YES;
employeeImageView.layer.cornerRadius = 5.0;
employeeImageView.layer.borderWidth = 1.0;
employeeImageView.layer.borderColor = [[UIColor grayColor] CGColor];
[headerView addSubview:employeeImageView];
UILabel *nameView = [[UILabel alloc] initWithFrame:CGRectMake(95, 35, 180, 20)];
nameView.text = employee.name;
nameView.font = [UIFont boldSystemFontOfSize:18];
[headerView addSubview:nameView];
UILabel *functionView = [[UILabel alloc] initWithFrame:CGRectMake(95, 55, 140, 16)];
functionView.text = employee.function;
functionView.textColor = [UIColor grayColor];
functionView.font = [UIFont systemFontOfSize:14];
[headerView addSubview:functionView];
[employeeImage release];
[employeeImageView release];
[nameView release];
[functionView release];
contactDetailsTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 370) style: UITableViewStyleGrouped];
contactDetailsTable.backgroundColor = [UIColor clearColor];
contactDetailsTable.tableHeaderView = headerView;
[headerView release];
contactDetailsTable.delegate = self;
contactDetailsTable.dataSource = self;
[self.view addSubview:contactDetailsTable];
}
- (void)viewDidUnload {
self.contactDetailsTable = nil;
self.employee = nil;
[super viewDidUnload];
}
- (void)viewWillAppear:(BOOL)animated {
[contactDetailsTable reloadData];
}
- (void)dealloc {
[contactDetailsTable release];
[employee release];
[super dealloc];
}
#pragma mark -
#pragma mark Table View Data Source Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 2;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;did
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *contactDetailIdentifier = #"contactDetailIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:contactDetailIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:contactDetailIdentifier] autorelease];
UILabel *leftLabel = [[UITextField alloc] initWithFrame:CGRectMake(5, 12, 70, 25)];
leftLabel.textAlignment = UITextAlignmentRight;
leftLabel.textColor = [UIColor grayColor];
leftLabel.tag = kLeftLabelTag;
leftLabel.userInteractionEnabled = NO;
[cell.contentView addSubview:leftLabel];
[leftLabel release];
UILabel *rightLabel = [[UITextField alloc] initWithFrame:CGRectMake(90, 12, 160, 25)];
rightLabel.font = [UIFont boldSystemFontOfSize:16];
rightLabel.tag = kRightLabelTag;
rightLabel.userInteractionEnabled = NO;
[cell.contentView addSubview:rightLabel];
[rightLabel release];
}
NSUInteger row = [indexPath row];
UILabel *leftLabel = (UILabel *)[cell viewWithTag:kLeftLabelTag];
UILabel *rightLabel = (UILabel *)[cell viewWithTag:kRightLabelTag];
switch (row) {
case kTelephoneRowIndex:
leftLabel.text = #"telefoon";
rightLabel.text = employee.phone;
break;
case kEmailRowIndex:
leftLabel.text = #"e-mail";
rightLabel.text = employee.email;
break;
default:
break;
}
return cell;
}
#pragma mark -
#pragma mark Table View Delegate Methods
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
return nil;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger row = indexPath.row;
if (row == 1) {
MFMailComposeViewController *mailController = [[MFMailComposeViewController alloc] init];
[mailController setToRecipients:[NSArray arrayWithObject:employee.email]];
[mailController.navigationBar setTintColor:[UIColor blackColor]];
[self presentModalViewController:mailController animated:YES];
mailController.mailComposeDelegate = self;
[mailController release];
}
NSLog(#"Row selected is: %d", row);
}
#pragma mark -
#pragma mark MFMailCompose View Delegate Methods
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
[self dismissModalViewControllerAnimated:YES];
}
#end
Check the doc for tableView:willSelectRowAtIndexPath::
Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected.
You are returning nil, basically saying the table view that you don't want that row selected. Therefore tableView:didSelectRowAtIndexPath: is not called.
When I had this problem I found the solution was to use willSelectRowAtIndexPath. In other places in the same project didSelectItemAtIndexPath is getting called fine.
#pragma mark - UITableViewDelegate
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// for some reason this is getting called instead of didSelectItemAtIndexPath
[self viewDetails:indexPath.row];
return indexPath;
}
- (void)tableView:(UITableView *)tableView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
// [self viewDetails:indexPath.row];
}