UITextField - crash on delegates that return BOOL - iphone

I have a UITextField that I am adding to a UITableViewCell to use as a search field for a long list of accounts. I have added it as follows:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
if ((indexPath.section < accountsection) && (hasSearch) && (indexPath.row == 0))
{
// Search
if (!searchField)
{
searchField = [[UITextField alloc] initWithFrame:CGRectMake(20, 10, cell.frame.size.width - 40, 25)];
[searchField setEnabled:YES];
searchField.placeholder = NSLocalizedString(#"Search", #"search");
searchField.keyboardType = UIKeyboardTypeDefault;
searchField.returnKeyType = UIReturnKeySearch;
searchField.autocorrectionType = UITextAutocorrectionTypeNo;
searchField.clearButtonMode = UITextFieldViewModeAlways;
searchField.delegate = self;
[cell addSubview:searchField];
[searchField release];
}
// Clean up an account label if needed
cell.accessoryType = UITableViewCellAccessoryNone;
cell.textLabel.text = #"";
cell.detailTextLabel.text = #"";
// Show the search field if it was hidden by a text label
searchField.hidden = NO;
[cell bringSubviewToFront:searchField];
}
}
To detect edits to the text field, I have set up the UITextFieldDelegate in the header and trap the following delegate calls:
#interface AccountViewController : UITableViewController <UITextFieldDelegate> {
BOOL hasSearch;
UITextField *searchField;
...
}
In the implementation, I then handle these delegate methods:
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
NSLog(#"Done editing");
[self filterAccountsBy:textField.text];
[textField resignFirstResponder];
return NO;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSLog(#"Searching for %#", string);
[self filterAccountsBy:string];
return YES;
}
However in the second one, unless I return YES, the text never changes; in the first one, returning YES seems to not affect me. But when I return YES in either, I get a nasty EXC_BAD_ACCESS.
I must be missing something in my manual adding of this UITextField to my cell but I can't figure out what it is... can anyone assist?
Many thanks.
EDIT: As suggested below, I commented out the filterAccounts call and my app now no longer crashes. Here is the full code for this method:
- (void)filterAccountsBy:(NSString *)filterstring
{
[accounts removeAllObjects];
if (([filterstring length] == 0) && (!isChooser) && (![vpmsConn isDomainLogon])) {
[accounts addObject:[[vpmsConn accounts] objectAtIndex:0]];
}
if ([filterstring length] == 0) {
[accounts addObjectsFromArray:[cache accounts]];
} else {
for (AccountItem *ac in [cache accounts])
{
BOOL found = NO;
// Name search
if ([[ac.clientName uppercaseString] rangeOfString:[filterstring uppercaseString]].location != NSNotFound) {
found = YES;
}
//more similar searches
if (found) {
[accounts addObject:ac];
}
}
}
[self.tableView reloadData];
}
I am a bit confused, though. When I filter this list using the textFieldShouldReturn and then return NO, it filters properly and does not crash. Something about returning YES from either one of these methods causes the crash after I have filtered. If I have not filtered at all, returning YES is no problem.
Let me know if there is any other code that I should post.

I have resolved the issue but I cannot (due to NDA) post the answer here yet. Those interested, and in the paid iOS developer program, should go to the NDA developer forums and search for UITextField EXC_BAD_ACCESS and you will find the answer...

in
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
where is
return cell;
?

I think your UITextField searchfield is begin deallocated. If you use self.searchField to set your searchfield (assuming it's a retained property), that will solve it.
I'm not sure what the rest of your .h looks like. You could do:
#property (nonatomic, retain) UITextField *searchField;
Then in the .m:
#synthesize searchField;
That's what I mean by making search field a retained property. This way your class will keep the search field around.

In - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPathreturn cell;
Donot release serachfield in the event;
Release in dealloc
add #property (nonatomic, retain) UITextField *searchField;

Related

How do I retrieve UITableView row number of a UISwitch?

I have tried several approaches posted here, but I cannot get my table full of switches to return an index value for the cell of the changed switch. I am creating the view containing the table programmatically (no xib).
TableSandboxAppDelegate.m I instantiate the view controller in didFinishLaunchingWithOptions: with:
...
TableSandboxViewController *sandboxViewController = [[TableSandboxViewController alloc]
init];
[[self window] setRootViewController:sandboxViewController];
...
TableViewController.h file reads:
#interface TableSandboxViewController : UITableViewController
{
NSMutableArray *_questionOrder;
NSMutableArray *switchStates;
}
#end
TableViewController.m cellForRowAtIndexPath: reads:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MainCell"];
UISwitch *theSwitch = nil;
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:#"MainCell"];
theSwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
theSwitch.tag = 100;
[theSwitch addTarget:self action:#selector(switchChanged:)
forControlEvents:UIControlEventValueChanged];
[cell.contentView addSubview:theSwitch];
} else {
theSwitch = [cell.contentView viewWithTag:100];
}
if ([[switchStates objectAtIndex:indexPath.row] isEqualToString:#"ON"]) {
theSwitch.on = YES;
} else {
theSwitch.on = NO;
}
return cell;
TableViewController.m -(IBAction)switchChanged:(UISwitch *)sender reads:
UITableViewCell *theParentCell = [[sender superview] superview];
NSIndexPath *indexPathOfSwitch = [self.tableView indexPathForCell:theParentCell];
NSLog(#"Switch changed at index: %d", indexPathOfSwitch.row);
My log result is always "Switch changed at index: 0". I feel like the problem is in that CGPoint line where I've tried combinations of replacements for "sender" ([sender superview], [[sender superview]superview], etc). I don't feel like that line is pointing to the view that displays the table.
What am I doing wrong?
Note added 10/9, 9:15 EDT: my goal is to be able to handle about 100 yes/no questions in the table, so reuse is a key. I want to scroll and have the table the state of each switch, as well as be able to retrieve them when leaving the view.
Tags is an okay solution, but a little clumsy because the cells - and therefore their subviews - are continually being reused, changing their rows - and therefore the tags they need.
Instead, I generally keep one of these around:
- (NSIndexPath *)indexPathWithSubview:(UIView *)subview {
while (![subview isKindOfClass:[UITableViewCell self]] && subview) {
subview = subview.superview;
}
return [self.tableView indexPathForCell:(UITableViewCell *)subview];
}
Then when I get an IBAction:
- (IBAction)someSubviewAction:(id)sender {
NSIndexPath *indexPath = [self indexPathWithSubview:(UIView *)sender];
// carry on from here
}
You may set switch view tag to row index. Instead of theSwitch.tag = 100;
do
-(UITableViewCell*)tableView:table cellForRowAtIndexPath:indexPth
{
UISwitch *theSwitch = nil;
if (cell == nil) {
...
// as per your example
[cell.contentView addSubview:theSwitch];
} else {
theSwitch = subviewWithClass(cell.contentView, [UISwitch class]);
}
theSwitch.tag = indexPath.row;
...
}
Add this helper function to replace viewWithTag: call
UIView *subviewWithClass(UIView *contentview, Class klass)
{
for (UIView *view in contentview.subviews)
if ([view isKindOfClass:klass])
return view;
return nil;
}
Then retrieve tag, that is a row index now, in your switchChanged function
-(IBAction)switchChanged:(UISwitch *)sender {
NSLog(#"Selected Switch - %d", sender.tag);
...
}
If you use something block-based (like https://github.com/brightsoftdev/iOS-Block-Based-Bindings/blob/master/UISwitch%2BBindings.m), you don't need to worry about getting the row, because you can reference the indexPath that is passed into tableView:cellForRowAtIndexPath: in your block.
Similar to #danh, I've come up with this solution using an extention which I've used multiple times.
#interface UIView (Find)
- (id)findSuperviewOfClass:(Class)class;
- (NSIndexPath *)findIndexPath;
#end
#implementation UIView (Find)
- (id)findSuperviewOfClass:(Class)class
{
return [self isKindOfClass:class] ? self : [self.superview findSuperviewOfClass:class];
}
- (NSIndexPath *)findIndexPath
{
UITableView *tableView = [self findSuperviewOfClass:[UITableView class]];
return [tableView indexPathForCell:[self findSuperviewOfClass:[UITableViewCell class]]];
}
#end
for iOS6+ you could maintain a NSMutableArray queuedSwitches
in -tableView:cellForrowAtIndexPath: you would take a switch, if not empty and places it on the custom cell and assign it to a property. If empty you create a new one.
in -tableView:didEndDisplayingCell:forRowAtIndexPath: you would add it to quededSwitches and remove it from it cell.
This will just allocate enough switches for visible cells and reuse them.
the switches are all wired up to one action.
-(void)switchAction:(UISwitch *)switch
{
NSIndexPath *indexPath = [self.tableView indexPathForCell:[switch superView]];
//…
}
You could create a subclass of UISwitch and add an indexPath property, then just set the indexPath in cellForRowAtIndexPath:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
SwitchCell *returnCell = [tableView dequeueReusableCellWithIdentifier:#"SwitchCell" forIndexPath:indexPath];
returnCell.switch.indexPath = indexPath;
return returnCell;
}

TableView is not loading data?

In my Map application I have segment controller on main screen and using that I have Map View & tableview(both are UIView). I have tried everything but my data is not loading in my tableview. Here is my tableview code. Here marker is attribute in my xml file which contain Showroom name and Iam able to parse this.
.h file
#interface HViewController : UIViewController<UITableViewDataSource, UITableViewDelegate> {
UITableView *_tableView;
}
#property (nonatomic, retain) IBOutlet UITableView *_tableView;
#end
.m file
Edited = with ViewWillAppear,viewDieLoad, segement action method
#synthesize tableView;
- (void)viewDidLoad {
appDelegate = (HAppDelegate *)[[UIApplication sharedApplication] delegate];
[segmentedControl addTarget:self action:#selector(segmentAction:)
forControlEvents:UIControlEventValueChanged];
}
- (void)viewWillAppear:(BOOL)animated
{
self._tableView.rowHeight = 80.0;
[_tableView reloadData];
}
-(void)segmentAction:(id)sender;{
UISegmentedControl* segCtl = sender ;
if( [segCtl selectedSegmentIndex] == 0 )
{
NSLog(#"segmentAction mapView");
mapView.hidden = NO;
_tableView.hidden = YES;
//[ self.view addSubview:mapView] ; // adding view to segmentindex 0
}
if( [segCtl selectedSegmentIndex] == 1 )
{
NSLog(#"segmentAction _tableview");
_tableView.hidden = NO;
mapView.hidden = YES;
//[ self.view addSubview:_tableview] ;
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSLog(#"appDelegate.markers _tableview");
return [appDelegate.markers count];
}
//method to print row(showroom count on Header)
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection: (NSInteger)section {
if(section == 0)
return [NSString stringWithFormat:NSLocalizedString(#"ShowRooms[%d]", #"Showroom format"), [appDelegate.markers count]];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
static NSUInteger const kShowroomNameLabelTag = 2;
UILabel *ShowroomNameLabel = nil;
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleGray;
ShowroomNameLabel = [[[UILabel alloc] initWithFrame:CGRectMake(50, 1, 300, 20)] autorelease];
ShowroomNameLabel.tag = kShowroomNameLabelTag;
ShowroomNameLabel.font = [UIFont boldSystemFontOfSize:18];
[cell.contentView addSubview:ShowroomNameLabel];
NSLog(#"UITableViewCell.markers _tableview");
}
else
{
ShowroomNameLabel = (UILabel *)[cell.contentView viewWithTag:kShowroomNameLabelTag];
}
marker *aMarker = [appDelegate.markers objectAtIndex:indexPath.row];
//ShowroomNameLabel.text = aMarker.name;
ShowroomNameLabel.text= [NSString stringWithFormat:#"ShowroomName= %#", aMarker.name];
return cell;
}
In my tableview Header it shows data count correctly but not showing data.
I have connected delegate,datasource,_tableview to fileOwner of the HViewController in which I have put above code. Plz suggest something where I am wrong. I am parsing XML file and getting data in console alos I can show it on Map. But I am not able to load data in my tableview.
Try moving [_tableView reloadData] to viewWillAppear.
UITableViewController reloads the table view's data in viewWillAppear, not viewDidLoad. I can't tell you the exact reason for which this would make a difference, though I can think of several. Anyway, it's worth a try.
EDIT:
RESPONSE TO COMMENTS
If titleForHeaderInSection: is being called, then there is a data source connected to a table view. So, the problem is not a lack of a data source connection.
I am guessing you have 2 table views in your .xib file: a large one & a short one below it. The large table view is not connected to the data source, so it just displays blank lines. The short table view is connected to the data source. But, it is just tall enough for a header and has no space left to display any cells. Thus, titleForHeaderInSection: is called, but cellForRowAtIndexPath: is not because there is no space to display any cells.
Note that this is just a guess, but it is the only scenario I can think of that would cause the behavior you described. The code you posted looks ok, although a bit more complicated than necessary.
There is no question that reloadData should be in viewWillAppear. That's where the Apple engineers put it when they created the UITableViewController class. So, to put it elsewhere, you have to believe you know better than they do.

How to get the text field values in the Table view in iPhone?

I have created login page which contains the user name and password. I created one custom cell and it has one label and one text field. And i have created one grouped table view and used the custom cell. Actually i have created successfully but the problem is, how can i get the text field values for user name and pass word. Bcoz i have used only one textfield for both fields. I couldn't get the textfield values properly. I always get the last value for both fields. How can i get the user name and pass word text values properly?
Here my sample code,
In custom Cell,
#interface CustomCell : UITableViewCell {
UILabel *userLbl;
UITextField *userTxt;
}
#property (nonatomic, retain) IBOutlet UILabel *userLbl;
#property (nonatomic, retain) IBOutlet UITextField *userTxt;
#end
In Root View Controller,
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:nil options:nil];
for(id currentObjects in nibObjects)
{
if([currentObjects isKindOfClass:[CustomCell class]])
{
cell = (CustomCell *) currentObjects;
}
}
}
if (indexPath.section == 0) {
if(indexPath.row == 0)
{
[[cell userLbl] setText:#"User Name:"];
cell.userTxt.tag = 0;
//self.userName = [[cell userTxt] text];
}
if (indexPath.row == 1) {
[[cell userLbl] setText:#"Pass Word:"];
cell.userTxt.secureTextEntry = YES;
//self.passWord = [[cell userTxt] text];
cell.userTxt.tag = 1;
}
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
// Configure the cell.
return cell;
}
-(IBAction) submitAction : (id) sender
{
self.userName = [[cell userTxt] text];
self.passWord = [[cell userTxt] text];
[cell.userTxt resignFirstResponder];
NSLog(#"The user Name is %#", self.userName);
NSLog(#"The password is %#", self.passWord);
//Doesn't work
/* UITextField *txtField = (UITextField*)[cell viewWithTag:0];
self.userName = [txtField text];
UITextField *txtField1 = (UITextField*)[cell viewWithTag:1];
self.passWord = [txtField1 text];
NSLog(#"The user Name is %#", self.userName);
NSLog(#"The password is %#", self.passWord);*/
}
Here my screen shot of the image is,
PLease Help me out.
Thanks.
You could use the textFieldShouldEndEditing method if you are using more than one textfield as the textFieldShouldReturn method will only get the string from the textfield that resigns FirstResponder and thus you will miss all other textfields. This is what I used in my recent project when i had a form built with the tableview and textfields. It had me puzzled for a while.
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
switch (textField.tag)
{
case 0:
userName = textField.text;
break;
case 1:
passWord = textField.text;
break;
}
return YES;
}
use tag for each text field and the call -
UITextField *txtField = (UITextField*)[cell viewWithTag:tag];
NSString *text = [txtField text];
and also 7KV7 is right you are assigning same tag to both text fields.
Why not do it elegantly? In your UITextFieldDelegate method, do it like this:
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
switch (textField.tag) {
case 0:
self.userName = textField.text;
break;
case 1:
self.passWord = textField.text;
break;
default:
break;
}
}
That way, you already have the data when the user clicks submit. Just a thought.
I think there is some problem in the way you set the tag for the textfields. I guess both have the same tags 1. Pls see if changing that helps
UPDATE
By the way how can you access the cell within the method submitAction. I think its easier to assign the text in textfields to an instance variable say username and password and use that in your method.

UITableView not getting populated

I have a peculiar problem. I created a normal Objective C class called SampleTable. I then extended UITableView instead of NSObject. Then in the initWithFrame constructor I initialized the table. I also made a NSMutableArray object for the datasource. I also conformed UITableViewDelegate and UITableViewDatasource. I have overridden the necessary methods also.
Now I made an object of this class in another class, and added the object as a subview. The tableView is getting drawn according to the CGRectMake() coordinates I gave to the initWithFrame constructor. But it is not getting populated with the data. I don't know what the problem is.
SampleTable.h
#import <Foundation/Foundation.h>
#interface SampleTable : UITableView {
NSMutableArray *ItemArray;
}
#property (nonatomic,retain) NSMutableArray *ItemArray;
-(NSMutableArray *) displayItemArray;
#end
SampleTable.m
#import "SampleTable.h"
#implementation SampleTable
#synthesize ItemArray;
-(id)initWithFrame:(CGRect)frm {
[super initWithFrame:frm];
self.delegate=self;
self.dataSource=self;
[self reloadData];
return self;
}
-(NSMutableArray *) displayItemArray {
if(ItemArray==nil) {
ItemArray=[[NSMutableArray alloc] initWithObjects:#"1",#"2",#"3",#"4",#"5",nil];
}
return ItemArray;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [ItemArray count];
}
-(UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell==nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
[cell autorelease];
}
NSString *temp=[self.ItemArray objectAtIndex:indexPath.row];
cell.textLabel.text = temp;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"didselect");
}
-(void) dealloc {
[ItemArray release];
[super dealloc];
}
#end
You did never initialize the ItemArray within your code snippet. Remove the displayItemData method and change the initializer towards:
-(id)initWithFrame:(CGRect)frm
{
if ((self = [super initWithFrame:frm])) != nil)
{
self.delegate=self;
self.dataSource=self;
ItemArray=[[NSMutableArray alloc] initWithObjects:#"1",#"2",#"3",#"4",#"5",nil];
[self reloadData];
}
return self;
}
You could also simply call that displayItemArray method within the initializer. I feel that method makes no sense as it stands and hence my recommendation to remove it altogether.
Without trying it myself, I am still pretty confident that you can also get rid of that [self reloadData] within the initializer.
During the -(id)initWithFrame:(CGRect)frm method your code calls -reloadData on the UITableView. At this point in time your ItemArray is not available.
Therefore, when UITableView calls it's delegates -numberOfSectionsInTableView: and -tableView:numberOfRowsInSection: methods to get information on what to display in the view, they return one section with zero rows.
Nothing displayed!
It might be a (one) solution to change your initialization of the ItemArray:
-(NSMutableArray *) displayItemArray {
if(ItemArray==nil) {
ItemArray=[[NSMutableArray alloc] initWithObjects:#"1",#"2",#"3",#"4",#"5",nil];
[self reloadData];
}
return ItemArray;
}
print value of
[self.ItemArray objectAtIndex:indexPath.row];
in NSLog... check wether it prints valid value or not....It seems that array's object releasing somewhere before it..

Reusable TableView header views

For performance sake it is usual to reuse UITableView' cells.
Is there a way to do the same thing with TableView header' views?
I am talking about the ones that are returned with delegate's method:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
I tried to do the following which doesn't seem to be working as expected:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
static NSString *CellIdentifier = #"Header";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: CellIdentifier];
if (cell == nil) {
cell = [self getHeaderContentView: CellIdentifier];
}
return cell;
}
Is there a way to reuse header' views?
The reason Apple built in the ability to reuse tableview cells is because while the tableview may have many rows, only a handful are displayed on screen. Instead of allocating memory for each cell, applications can reuse already existing cells and reconfigure them as necessary.
First off, header views are just UIViews, and while UITableViewCell is a subclass of UIView, they are not intended to be placed as the view of a section header.
Further, since you generally will have far fewer section headers than total rows, there's little reason to build a reusability mechanism and in fact Apple has not implemented one for generic UIViews.
Note that if you are just setting a label to the header, you can use -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section instead.
For something more custom, such as a label with red text (or a button, image, etc), you can do something like this:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0,0, 320, 44)] autorelease];
UILabel *label = [[[UILabel alloc] initWithFrame:headerView.frame] autorelease];
label.textColor = [UIColor redColor];
label.text = [NSString stringWithFormat:#"Section %i", section];
[headerView addSubview:label];
return headerView;
}
You can implement that by creating UITableViewHeaderFooterView class
it is subclass of UIView
You also need to create an individual XIB as it will not be created automatically with UITableViewHeaderFooterView creation.
Register Nib with tableview
[self.tblCart registerNib:[UINib nibWithNibName:#"CartHeaderView" bundle:nil] forHeaderFooterViewReuseIdentifier:#"CartHeader"];
Now You can Access that in viewForHeaderInSection
-(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
CartHeaderView *sectionHeader=[tableView dequeueReusableHeaderFooterViewWithIdentifier:#"CartHeader"];
return sectionHeader;
}
Note :
To set background color you will need to create a subview with same frame as section header and set color for that view.
you can follow
Changing the background color on a UITableViewHeaderFooterView loaded from a xib says to use contentView.backgroundColor instead
A simple yet effective solution:
#interface SectionedTableViewController ()
#property (nonatomic, strong) UINib* sectionHeaderNib;
#property (nonatomic, strong) NSMutableArray* sectionHeaders;
#end
#implementation SectionedTableViewController
#synthesize sectionHeaderNib = sectionHeaderNib_;
#synthesize sectionHeaders = sectionHeaders_;
- (void) viewDidUnload
{
self.sectionHeaders = nil;
[super viewDidUnload];
}
- (NSMutableArray*) sectionHeaders
{
if (!sectionHeaders_)
self.sectionHeaders = [NSMutableArray array];
return sectionHeaders_;
}
- (UINib*) sectionHeaderNib
{
if (!sectionHeaderNib_)
self.sectionHeaderNib = [UINib nibWithNibName: NSStringFromClass(YourHeaderView.class) bundle: nil];
return sectionHeaderNib_;
}
- (YourHeaderView*) dequeueHeader
{
return [self.sectionHeaders firstObjectPassingTest: ^(id obj) { return (BOOL) ([obj superview] == nil); }];
}
- (NSString*) sectionHeaderTitleForSection: (NSInteger) section
{
return nil;
}
- (UIView*) tableView: (UITableView*) tableView viewForHeaderInSection: (NSInteger) section
{
YourHeaderView* headerView = [self dequeueHeader];
if (!headerView)
{
headerView = [YourHeaderView instanceFromNib: self.sectionHeaderNib];
[self.sectionHeaders addObject: headerView];
}
return headerView;
}
#end