Creating A TableVIew Programmatically With Objective-C iOS - iphone

I'm new to developing iOS applications and Objective C itself, so I have a probably very simple question.
Currently I have the following method that is called from a ToolBar Button click. The method is designed to create a table view in the frame variable fr.
- (IBAction)addGolfer:(id)sender {
CGRect fr = CGRectMake(101, 45, 100, 416);
UITableView *tabrleView = [[UITableView alloc]
initWithFrame:fr
style:UITableViewStylePlain];
tabrleView.autoresizingMask =
UIViewAutoresizingFlexibleHeight |
UIViewAutoresizingFlexibleWidth;
tabrleView.delegate = self;
tabrleView.dataSource = self;
[tabrleView reloadData];
self.view = tableView;
}
The result of calling this method is not what I expect. Instead of creating the Table View in the frame "fr", the table view fills the entire screen.
Again I'm totally new and would a appreciate any answers and any suggestions. Thanks!

When you set dataSource and delegate properties for your UITableView, it means, you have to write at least this methods for dataSource:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
If you wouldn't do this, it will be crash. Summary you'll get this (this code may contain syntax or logic errors - I wrote it in notepad):
#interface YourViewController : UIViewController <UITableViewDataSource, UITableViewDelegate> {
UITableView *firstTableView;
UITableView *secondTableView;
}
#end
//
#implementation YourViewController
#pragma mark - Objects Processing
- (void)addGolfer:(UIBarButtonItem *)sender {
if (secondTableView) {
[secondTableView removeFromSuperView];
secondTableView = nil;
}
secondTableView = [[UITableView alloc] initWithFrame:CGRectMake(101, 45, 100, 416)];
secondTableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
secondTableView.delegate = self;
tabrleView.dataSource = self;
[self.view addSubview:secondTableView];
}
#pragma mark - TableView DataSource Implementation
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView == firstTableView) { // your tableView you had before
return 20; // or other number, that you want
}
else if (tableView == secondTableView) {
return 15; // or other number, that you want
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
cell.backgroundView = [[UIView alloc] init];
[cell.backgroundView setBackgroundColor:[UIColor clearColor]];
[[[cell contentView] subviews] makeObjectsPerformSelector:#selector(removeFromSuperview)];
if (tableView == firstTableView) { // your tableView you had before
// ...
}
else if (tableView == secondTableView) {
cell.titleLabel.text = [NSString stringWithFormat:#"Cell %d", indexPath.row + 1];
}
return cell;
}
#end

Step 1: Add delegate UITableViewDataSource,UITableViewDelegate
#interface viewController: UIViewController<UITableViewDataSource,UITableViewDelegate>
{
UITableView *tableView;
}
Step 2:
-(void)viewDidLoad
{
tableView=[[UITableView alloc]init];
tableView.frame = CGRectMake(10,30,320,400);
tableView.dataSource=self;
tableView.delegate=self;
tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"Cell"];
[tableView reloadData];
[self.view addSubview:tableView];
}
Step 3: Properties for tableview (rows & column)
//-- For no of rows in table
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 10;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
//-- Table header height if needed
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 50;
}
//-- Assign data to cells
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath] ;
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text=[your_array objectAtIndex:indexPath.row]; ***(or)*** cell.textLabel.text = #"Hello";
return cell;
}
//-- Operation when touch cells
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Your custom operation
}

Instead of setting the view of the UIViewController, add the tableView as a subview.
Instead of:
self.view = tableView;
Do this:
[self.view addSubview:tableView];
This will properly respect the frame that you set.

Related

UITableViewCell keeps getting deselected

I have a strange problem with UITableView:
My tableview shows the names of objects from which the user can select one. The value is saved. When the tableview comes up the row is selected (in cellForRowAtIndexPath). But in viewWillAppear the row is first selected and then deselected. You can see that it is first selected because of a the blue background occurs for a short time.
I have set
self.clearsSelectionOnViewWillAppear = NO;
but that does not work ether. Can someone help me out please! Thanks in advance.
Here some sample code:
#import "ECTESTTableViewController.h"
#interface ECTESTTableViewController ()
#end
#implementation ECTESTTableViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.clearsSelectionOnViewWillAppear = NO;
}
#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 8;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
// cell.selectionStyle = UITableViewCellSelectionStyleNone;
//cell.backgroundColor = [UIColor redColor];
}
if (indexPath.row == 1)
{
// cell.accessoryType = UITableViewCellAccessoryCheckmark;
NSLog(#"select %d", indexPath.row);
cell.selected = TRUE;
}
else {
// cell.accessoryType = UITableViewCellAccessoryNone;
cell.selected = FALSE;
}
cell.textLabel.text = [NSString stringWithFormat:#"row %d", indexPath.row];
return cell;
}
#end
If you want to programatically select a row in a UITableView use:
- (void)selectRowAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated scrollPosition:(UITableViewScrollPosition)scrollPosition
Don't be setting the selected states of the cells.
Write following code
NSIndexPath *indexPath = [tableView indexPathForSelectedRow];
[tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition: UITableViewScrollPositionNone];

How to add a custom view on selected cell

I want to add a view on selected cell of tableview. I'm writing this code.
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
UIView *myView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 200)];
myView.backgroundColor=[UIColor greenColor];
myView.tag=1001;
[cell.contentView addSubview:myView];
}
after writing this code my other cells are not showing due to this view. I want to increase selected cell's height to 200 and add my custom view on selected cell.
can anyone tell me how to do this,,
thanks in advance.
Create a property of the selected cell
#property (nonatomic) int currentSelection;
Then initialize it here
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.currentSelection = -1;
}
In heightForRowAtIndexPath you can set the height you want for the selected cell
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
int rowHeight;
if ([indexPath row] == self.currentSelection) {
rowHeight = 200;
}
else
rowHeight = CURRENT_HEIGHT_HERE;
return rowHeight;
}
Then add you view here and hide it as:
// Customize the appearance of table view cells.
- (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] ;
}
UIView *myView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 200)];
myView.backgroundColor=[UIColor greenColor];
myView.tag=1001;
[myView setHidden:YES];
[cell.contentView addSubview:myView];
// Configure the cell.
return cell;
}
In didSelectRow you save the current selection and save a dynamic height, if required
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// do things with your cell here
// set selection
self.currentSelection = indexPath.row;
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
[[cell viewWithTag:1001] setHidden:NO];
// animate
[tableView beginUpdates];
[tableView endUpdates];
}
ok as i told u better u need to subclass the UITableViewCell in the following example, when selecting the cell it will add custom view to selected cell better u go through this and change it according to your requirement . Hope this helps u :)
//in subclassed cell "CustomCell.h" file
#interface CustomCell : UITableViewCell
{
UIView *aView; //to hold ur view
BOOL addView; //to check wheather to add view or not
}
#property(nonatomic, retain) UIView *aView;
#property(nonatomic, assign) BOOL addView;
#end
//in "CustomCell.m" file
#import "CustomCell.h"
#implementation CustomCell
#synthesize aView;
#synthesize addView;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
aView = [[UIView alloc]initWithFrame:CGRectZero]; //init the view with zero rect as if u want initially frame is zero
aView.backgroundColor = [UIColor greenColor]; //to know weather it is added or not
[self addSubview:aView];//added to cell
}
return self;
}
- (void)dealloc
{
[aView release];
[super dealloc];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)layoutSubviews
{
[super layoutSubviews];
if(self.addView) //if the view is added
{
self.aView.frame = CGRectMake(10, 3, 100,200);
}
else
{
self.aView.frame = CGRectZero;//if there is no view
}
}
//in your ViewController.h file
#interface ViewController : UIViewController<CountdownTimerDelegate>
#property (retain, nonatomic) IBOutlet UITableView *aTableView;
#property (nonatomic, retain) NSIndexPath *selectedIndexPath;
#end
//in ViewController.m file
#import"CustomCell" //add this to header file
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
CustomCell *cell = [self.aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell =[[CustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if(self.selectedIndexPath != nil)
{
if(self.selectedIndexPath.row == indexPath.row)
cell.addView = YES;
else
cell.addView = NO;
}
//initially set it no for all cell
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//in did select row at indexpath
self.selectedIndexPath = indexPath;
[self.aTableView reloadData];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(self.selectedIndexPath != nil)
{
if(self.selectedIndexPath.row == indexPath.row)
{
return 200;
}
return 45;
}
else
return 45;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
selectedIndex = indexPath.row;
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
myView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 200)];
myView.backgroundColor = [UIColor greenColor];
myView.tag = 1001;
[cell.contentView addSubview:myView];
[tableView reloadData];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
if ([indexPath row] == selectedIndex) {
return myView.bound.size.height;
}
else
return currentHeight;
}
Hope this will work.

tableview is crashing on clicking on cell or on scrolling in ios 5

I made a demo empty app and add a navigation controller with the view
UINavigationController *navBar = [[UINavigationController alloc]initWithRootViewController:objFirstViewControllerViewController];
[self.window addSubview:navBar.view];
After it i add a table view on the first view controller like this .
UITableView* demotableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 400) style:UITableViewStylePlain];
demotableView.delegate = self;
demotableView.dataSource = self;
[self.view addSubview:demotableView];
and the delegate function of the table view and main cell for row function like this way
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.textLabel.text = #"Hello this is sample text";
cell.textLabel.minimumFontSize = 12;
cell.textLabel.adjustsFontSizeToFitWidth = TRUE;
cell.textLabel.font = [UIFont fontWithName:#"Copperplate" size:18];
return cell;
}
But when i scroll on my table or click any cell to go on the next view it just crash and give these two error on clicking and scrolling respectively.
[__NSCFArray tableView:didSelectRowAtIndexPath:]
[__NSCFDictionary tableView:cellForRowAtIndexPath:]
I don't understand what is getting wrong this code it have been working with the prior os properly
Any body can help please ?
Here is the code for did select row
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
Second *anotherViewController = [[Second alloc] initWithNibName:nil bundle:nil];
[self.navigationController pushViewController:anotherViewController animated:YES];
}
and no of row is this one
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 15;
}
Actually I misused the ARC what are the changes I made to make the app run successfully actually it was crashing due to memory leak I reference the class in delegate with local object but the it got released when it tried to add the data on it and when table's delegate and datasource try to add the things in the current class it was released and it throw message from those message instances, I was stuck because I was thinking it is happening due to me having taken an empty kind of application but after adding the lines below in the delegate class I got the problem solved.
What I did in the delegate class in the .h file:
FirstViewControllerViewController *objFirstViewControllerViewController;
#property (strong, nonatomic) FirstViewControllerViewController *objFirstViewControllerViewController;
Then my table started behaving properly and all things that I was having problem in.
Replace your code by this and try:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = #"Hello this is sample text";
cell.textLabel.minimumFontSize = 12;
cell.textLabel.adjustsFontSizeToFitWidth = TRUE;
cell.textLabel.font = [UIFont fontWithName:#"Copperplate" size:18];
return cell;
}
Hope this helps.
Please try this....
add your table view like this..
productList = [[UITableView alloc] initWithFrame:CGRectMake(0,102, 320, 267) style:UITableViewStylePlain];
productList.delegate = self;
productList.dataSource = self;
productList.backgroundColor = [UIColor clearColor];
[self.view addSubview:productList];
and add these methods....
#pragma mark Table view data source
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return (your row count);
}
// Customize the appearance of table view cells.
- (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];
}
// Configure the cell.
cell.textLabel.text = #"Title";
cell.detailTextLabel.text = formattedString;
cell.detailTextLabel.textColor = [UIColor darkGrayColor];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
Second *anotherViewController = [[Second alloc] initWithNibName:nil bundle:nil];
[self.navigationController pushViewController:anotherViewController animated:YES];
}
Since you have set demotableView.delegate = self;
you have to implement the tabelView: didSelectRowAtIndexPath: function which solves the crash on selecting(on Click) a Cell.
To resolve the crash of scrolling, you hav to implement
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
method.
P.S: In the cellForRowAtIndexPath:, all the lines except cell.textLabel.text should be inside
if(cell == nil){
}
and please follow proper maemory management rules

table view containg image view

i ve got an imageview ..below the imageview is a table view..which loads the data from server.by default five fields in table view are visible ..works fine..if i m to scroll the table view to view the remaining fields..the scroller rebounces..wat i want is the table view to be fixed and not to rebounce when scrolled ..i d be so greatful if u guys cud help me out..below is the code..
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [items count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 28.0;
}
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0,
tableViewteam.bounds.size.width, 28)] autorelease];
headerView.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle]pathForResource:#"team"ofType:#"png"]]];
return headerView;
}
- (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] autorelease];
}
cell.selectionStyle=UITableViewCellSelectionStyleNone;
cell.imageView.backgroundColor=[UIColor clearColor];
cell.textLabel.text=[[items objectAtIndex:indexPath.row]objectForKey:#"title"];
cell.textLabel.textColor=[UIColor whiteColor];
cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
I didn't fully understand your problem. If you want to stop bouncing the table view you can add
yourTableView.bounces = NO;
in ViewDidLoad()
If you need your tableView to be fixed you can disable scrolling.
tableView.scrollEnabled = NO;

How can I implement a "double" UITextField?

I am trying to generate a UITextField in a view like this. I don't mind using IB or doing it programmatically.
(source: echofon.com)
New File(Cocoa Touch Class -> UIViewController subclass)
UITableViewController subclass, With XIB for interface(check both)
open Xib file
change the view style(plain->group) on Attributes Inspector(apple key + 1)
add following code in .m file
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 2;
}
- (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] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
if(indexPath.row == 0) {
cell.textLabel.text = #"Username";
UITextField *field = [[[UITextField alloc] initWithFrame: CGRectMake(120, 10, 180, 30)] autorelease];
[cell addSubview:field];
}
else if(indexPath.row == 1) {
cell.textLabel.text = #"Password";
UITextField *field = [[[UITextField alloc] initWithFrame: CGRectMake(120, 10, 180, 30)] autorelease];
field.secureTextEntry = YES;
[cell addSubview:field];
}
return cell;
}
- (NSString *)tableView: (UITableView *)tableView
titleForHeaderInSection: (NSInteger)section
{
return #"Account";
}
- (NSString *)tableView: (UITableView *)tableView
titleForFooterInSection: (NSInteger)section
{
return #"If you don't have a twitter account, go to twitter.com to sign up.";
}
You need to place the UITextField objects inside of a table to achieve this effect. See UITableView for more details: http://developer.apple.com/iphone/library/DOCUMENTATION/UIKit/Reference/UITableView_Class/Reference/Reference.html