UITableView cells are not displaying text - ios

I just finished a simple 5 minute UITableView tutorial. I even imported the tutorial's source code files into my own current xcode project, and I still cannot get this to work. I'm not sure if I'm doing something wrong, or if it's because the tutorial was created using a different version of xcode or what.
Anyways, I created a new objective-c file called "TVTViewController" which is a subclass of UIViewController. I then dragged a UIViewController onto the storyboard and set it's custom class in the attributes inspector to "TVTViewController".
Next, I dragged a UITableView object onto the UIViewController that I just dragged onto the storyboard.
I set the UITableView's "Content" setting to "Dynamic" and then set it's "Prototype Cells" setting to "1".
I then selected the prototype cell on the storyboard, and changed it's "Style" setting to "Subtitle", and changed it's "Identifier" setting to "SettingsCell".
Finally, here is my header file code:
#import <UIKit/UIKit.h>
#interface TVTViewController : UIViewController <UITableViewDataSource>
#end
And here is my main file's code:
#import "TVTViewController.h"
#interface TVTViewController ()
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#property (strong, nonatomic) NSArray *tweetsArray;
#end
#implementation TVTViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//1
self.tableView.dataSource = self;
//2
self.tweetsArray = [[NSArray alloc] initWithObjects:
#"Always put your fears behind you and your dreams in front of you.",
#"A relationship with no trust is like a cell phone with no service, all you can do is play games.",
#"People should stop talking about their problem and start thinking about the solution.",
#"Dear Chuck Norris, Screw you. I can grill burgers under water. Sincerely, Spongebob Squarepants.",
#"My arms will always be open for you, they will never close, not unless you're in them.",
nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//3
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.tweetsArray count];
}
//4
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//5
static NSString *cellIdentifier = #"SettingsCell";
//6
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
NSString *tweet = [self.tweetsArray objectAtIndex:indexPath.row];
//7
[cell.textLabel setText:tweet];
[cell.detailTextLabel setText:#"via Codigator"];
return cell;
}
#end
When I run my app on my iPhone, it shows the table view, but it is empty. None of the text is displayed in the table view's cells at all. This is pretty much copy and pasted from the tutorial's source code, and when I run the tutorial's source code app on my iPhone it displays the text in the cells just fine.
I don't understand why it is not working for me once I add the same code to my own app.
Thanks for the help.
EDIT:
I just figured it out on my own. The tutorial author neglected to tell you to connect the IBOutlet called "tableView" to the UITableView object. I just connected them and everything is displaying fine now. I would answer my own question but stackoverflow won't let me for another 8 hours.

A possible work around:
a) Check that the cell were actually created or not:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if( !cell )
{
cell = [[UITableViewCell alloc] init];
}
b) Set its delegate and datasource
Check out other ways to dequeue table view cells

Add UITableViewDelegate, like
#interface TVTViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
with
self.tableView.delegate = self;
And create cell as
if(cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

Related

Change image on click in custom table cell made from nib

I have a table with custom cells that are made from a nib file. When a user clicks a cell it expands in height , thus simulating a dropdown. In the custom cell there is an imageView that has a dropDown image when the cell is not clicked. However when the cell is clicked it should change the image to a collapse image or arrow up image to show that the cell is open.
I am having a problem changing the image when the cell expands from arrow down to arrow up and vice versa. I would like assistance achieving this.
Here is my code :
ViewController.h
#interface ViewController : UIViewController <UITableViewDelegate,
UITableViewDataSource>
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#property(nonatomic, strong) NSArray *items;
#property (nonatomic, assign) BOOL expandFlag;
#property (nonatomic, assign) NSIndexPath* selectedIndex;
ViewController.m
- (NSArray *) items
{
if (!_items) {
_items = [NSArray new];
}
return _items;
}
- (void)viewDidLoad {
[super viewDidLoad];
UINib *nib = [UINib nibWithNibName:#"CustomTableViewCell" bundle:nil];
[self.tableView registerNib:nib forCellReuseIdentifier:#"cell"];
_items = #[
#{#"title":#"Simpson", #"short":#"Homer", #"long":#"Mr jhvjm,b;k t tyfy rctrc rtcf rvty rthvgh bb r5ertvyg hg r5 tyhg 6ruygj 8rutyj r6yiugg tygdtjhgfdt hg tvt gthgfgni7yjftgjhb ftgfh b yjh gtfjfyhh j jj j", #"image":#"There are many ways to create expandable cells in the table view. Few of them you can easily find on this blog or somewhere in Google. One of that is the official Apple “Date cell” demo code. However, most of that describing the little hard way by using operations directly on constraints."},
#{#"title":#"Simpson", #"short":#"Marge", #"long":#"Mrs bjyvhm uikn o utv jb k", #"image":#"There are many ways to create expandable cells in the table view. Few of them you can easily find on this blog or somewhere in Google. One of that is the official Apple “Date cell” demo code. However, most of that describing the little hard way by using operations directly on constraints."},
#{#"title":#"Simpson", #"short":#"Bart", #"long":#"Mr vubj cbjknuy iubyuvjh biubkj ", #"image":#"There are many ways to create expandable cells in the table view. Few of them you can easily find on this blog or somewhere in Google. One of that is the official Apple “Date cell” demo code. However, most of that describing the little hard way by using operations directly on constraints."},
#{#"title":#"Simpson", #"short":#"Lisa", #"long":#"Miss jbjvjbbiuvu yuvhj uby ", #"image":#"There are many ways to create expandable cells in the table view. Few of them you can easily find on this blog or somewhere in Google. One of that is the official Apple “Date cell” demo code. However, most of that describing the little hard way by using operations directly on constraints."},
#{#"title":#"Simpson", #"short":#"Maggie", #"long":#"Miss iubniyujh k iuuh ", #"image":#"There are many ways to create expandable cells in the table view. Few of them you can easily find on this blog or somewhere in Google. One of that is the official Apple “Date cell” demo code. However, most of that describing the little hard way by using operations directly on constraints."},
#{#"title":#"Flanders", #"short":#"Ned", #"long":#"Mr hbuyvj iybkj nui uhc n", #"image":#"There are many ways to create expandable cells in the table view. Few of them you can easily find on this blog or somewhere in Google. One of that is the official Apple “Date cell” demo code. However, most of that describing the little hard way by using operations directly on constraints."}
];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void) didExpandCell{
_expandFlag = !_expandFlag;
[self.tableView reloadRowsAtIndexPaths:#[_selectedIndex] withRowAnimation:UITableViewRowAnimationAutomatic];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.items.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
NSDictionary *item = _items[indexPath.row];
cell.titleImage.text = [item objectForKey:#"title"];
cell.longLabel.text = [item objectForKey:#"long"];
cell.shortLabel.text = [item objectForKey:#"image"];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
_selectedIndex = indexPath;
[self didExpandCell];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
if (_expandFlag && _selectedIndex == indexPath) {
return 400;
}
return 200;
}
CustomeTableViewcell.h
#interface CustomTableViewCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UIImageView *thumbImage;
#property (weak, nonatomic) IBOutlet UILabel *titleImage;
#property (weak, nonatomic) IBOutlet UILabel *shortLabel;
#property (weak, nonatomic) IBOutlet UILabel *longLabel;
#property (weak, nonatomic) IBOutlet UIImageView *dropDownImage;
CustomerTableViewCell.m
- (void)awakeFromNib {
[super awakeFromNib];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
}
You should check and change dropDownImage in cellForRowAtIndexPath method. Something likes the code below
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
NSDictionary *item = _items[indexPath.row];
cell.titleImage.text = [item objectForKey:#"title"];
cell.longLabel.text = [item objectForKey:#"long"];
cell.shortLabel.text = [item objectForKey:#"image"];
NSString *dropDownImageName = [indexPath isEqual:_selectedIndex] && _expandFlag ? #"ARROW_DOWN" : #"ARROW_UP";
cell.dropDownImage.image = [UIImage imageNamed:dropDownImageName];
return cell;
}
Change ARROW_UP and ARROW_DOWN with your image names.

reload data in UITABLEVIEW object c when clicking button

I try to search this problem in this site and I found this link How to insert items to a UITableView when a UIButton is clicked in iOS. But my problem is, I already copy the code on that link and It doesn't reload the data when I insert a value to my array.
here's the code "ViewController.m"
#import "ViewController.h"
#interface ViewController ()
#property(nonatomic,strong) NSMutableArray * array;
#property(nonatomic,weak) IBOutlet UITableView * tableView;
#end
#implementation ViewController
-(NSMutableArray *) array{
if(_array==nil){
_array=[[NSMutableArray alloc] init];
}
return _array;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (IBAction)addInfo:(UIBarButtonItem *)sender {
[self.array addObject:#"sample"];
[self.tableView reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [self.array count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"TodoListItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
cell.textLabel.text = [self.array objectAtIndex:indexPath.row];
return cell;
}
#end
here's the code "ViewController.h"
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UITableViewDataSource,UITableViewDelegate>
#end
Is there something wrong with my code or there is something that I need to setup to my tableview? I'm very confuse of this and try to figure out the missing part of my code. I'm still studying the code of object c and I'm still noob for this. Please help me and thanks in advance.
How did you insert the UITableView?, on nib or programatically?, either way you need to flag the table's delegate and datasource, if on nib, right click on table and see that delegate and data source are connected to the files owner, if programatically check
self.MyTable.datasource = self
self.MyTable.delegate = self
please see how to check if connected [dataSource and delegate should be with a dot, if not click on circle and drag line to file's owner for both]
table delegate and datasource on interface builder "NIB"
Also please note that on this image outlet is not connected, you have to connected also to call the reload as you are doing now
edit, check if the button is connected?, put a log or a break point on ibaction for your button to know if is called
edit 2, you have to init the array, are you calling it? do this in view will appear or when you want to use it
edit 3, try this
- (IBAction)addInfo:(UIBarButtonItem *)sender {
if(self.array==nil){
self.array=[NSMutableArray array];
}
[self.array addObject:#"sample"];
[self.tableView reloadData];
}

How to display a table view implemented in another class

I would like to display different content in its corresponding views by using only one subclass for generating a custom table view. When the table view is being filled with data, I would like to send the whole view to a specific view and display it.
When I generate the table view on the displaying view controller there is no problem. Even I can transfer the table view from the displaying view controller to another view, but when I try to generate the table view in another class and try to call it from the the root view controller, I only get a initialised but empty table view.
Here is the code:
tableViewGenerator.h
#import <UIKit/UIKit.h>
#interface TableViewGenerator : UIViewController <UITableViewDataSource, UITableViewDelegate>
- (UITableView *) getTableViewForOtherVC;
#property (nonatomic, strong) IBOutlet UITableView *spreadSheet;
#end
tableViewGenerator.m
...
- (UITableView *) getTableViewForOtherVC {
if (!self.spreadSheet) {
self.spreadSheet = [[UITableView alloc]initWithFrame:CGRectMake(0., 0., self.view.frame.size.width, self.view.frame.size.height/2.5) style:UITableViewStyleGrouped];
}
UITableView *tableViewToBeTransfered = self.spreadSheet;
return tableViewToBeTransfered;
}
...
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 1;
}
- (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 = #"Test";
return cell;
}
displayingVC.m
#import "DisplayingVC.h"
#import "TableViewGenerator.h"
#interface CTTOVViewController ()
#end
#implementation CTTOVViewController
- (void)viewDidLoad{
[super viewDidLoad];
UITableView *spreadSheet1;
if (!spreadSheet1) {
TableViewGenerator *tableVC = [[TableViewGenerator alloc]init];
spreadSheet1 = [tableVC getTableViewForOtherVC];
[self.view addSubview:spreadSheet1];
}
}
...
#end
I suppose that I have done something wrong on the table filling but I can not find what.
Any hint will be highly appreciated.
Thank you in advance
You don't seem to be setting the table view's dataSource and delegate properties anywhere, so you need to have these properly set.
On a separate front, what you're trying to accomplish is probably much easier if you generate a model, instead of the UITableView itself. I recommend checking out the models provided by free Sensible TableView framework as these can save you a huge amount of time.

TableView within ViewController not displaying cells

I'm fairly new to iOS development and I've been wrestling with a solution for this for about a day now and can't figure out why it is not working. I am trying to use a tableview within a viewcontroller as a small menu for the user to use. I have checked to see if the NSArray is being populated, and it is. I have also checked to see if the cell is being created, and it is. I just can't figure why it is not populating the tableview with the cells it creates. Below is my the code that I have so far. Thanks in advance for any help anyone can provide.
MainViewController.h
#import <UIKit/UIKit.h>
#interface MainViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
#property (weak, nonatomic) IBOutlet UITableView *menuTableView;
#property (weak, nonatomic) IBOutlet UIButton *menuButton;
#property (strong, nonatomic) NSArray *menuItemsArray;
#property (weak, nonatomic) IBOutlet UILabel *menuLabel;
#end
MainViewController.m
#import "MainViewController.h"
#interface MainViewController ()
#end
#implementation MainViewController
#synthesize menuItemsArray, menuTableView, menuButton, menuLabel;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//Set TableView Delegate/DataSource to self
[self.menuTableView setDelegate:self];
[self.menuTableView setDataSource:self];
[self.menuTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
[self.menuTableView setBounces:NO];
[self.menuTableView setRowHeight:self.menuLabel.frame.size.height];
self.menuItemsArray = [[NSArray alloc] initWithObjects:#"Add Category", #"Add Item", #"Settings", nil];
NSLog(#"array: %#", menuItemsArray);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#pragma mark - UITableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return ([self.menuItemsArray count]);
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"menuCell"];
[[cell textLabel]setText:[self.menuItemsArray objectAtIndex:indexPath.row]];
[[cell textLabel]setFont:[self.menuLabel font]];
return cell;
}
-(void)tableView:(UITableView *)tableview didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[self.menuTableView deselectRowAtIndexPath:indexPath animated:YES];
NSString *selectedString = [self.menuItemsArray objectAtIndex:indexPath.row];
self.menuLabel.text = selectedString;
}
I had the same problem, my table view was not getting displayed within a view controller.
I have found a solution.
You can create another view controller with a Container view on it. And put ur table view on a Table View controller. just embed the table view controller to the container view of ur mail view controller.
Make sure your initWithNib method is being called. If you are calling [[MainController alloc] init] your "menuTableView" will never be created from the Nib. Also, double-check the table view by setting the backgroundColor of the main table view to [UIColor red] or something just to make sure the tableView is present and that it has the frame you expect. It might be sitting behind one of your other views, have a frame of (0,0,0,0), or not be present in the view at all.
Also try calling [self.menuTableView reloadData] at the end of your 'viewDidLoad' or initialize the menuItemsArray before you set the data source and delegate (i.e. in your initWithNib method).
And when you do get it all working (you are very close) you will want to change your cellForRow method to something more like this:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:#"menuCell"];
if(!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"menuCell"];
}
[[cell textLabel]setText:[self.menuItemsArray objectAtIndex:indexPath.row]];
[[cell textLabel]setFont:[self.menuLabel font]];
return cell;
}
This will allow you to take advantage of the cell reuse that makes table views so efficient.
This is a bit late as you have found a way around it but I was having the same problem as you and found that I needed to connect the IBOutlet property to the table view in storyboard and then it all worked.
I hope this helps you in future.
One cause of the symptoms described is if you have placed the UITableView in the parent view using a container view in a storyboard, but are initialising and populating in code a different instance of the UITableView than the one that is actually being presented to the user. If you have placed the UITableView within the view using a container view, then you need to do the following:
Connect the UITableView to the container view with a segue, by Control-Dragging from the container view to the UITableView in the Storyboard.
Click on the segue, and give it a name e.g. tableViewSegue.
Set up the table by implementing prepareForSegue:sender:
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
NSString * segueName = segue.identifier;
if ([segueName isEqualToString: #"tableViewSegue"]) {
UIViewController * myTableView = [segue destinationViewController];
// Do any table setup here, such as injecting the data array into a property on the tableView.
}
}
If instead you have been creating a different UITableView in code, what you will see is an unpopulated UITableView that follows the specifications set up in the storyboard (e.g., row height spacing will be correct) and which is responding to user interaction, but is empty. The empty one is the one being initialised automatically for you by the storyboard, and meanwhile you've been creating another UITableView somewhere else:
// DON'T DO IT THIS WAY IF YOU'RE USING STORYBOARD.
- (void)viewDidLoad {
[super viewDidLoad];
// Incorrectly creating a tableview child table view that won't be the one presented.
self.myTableView = [MYTableViewClass new];
// ...further configuration of the table.
}
If you follow this incorrect path, the other UITableView you are creating is being built in memory, and populated with your data array, so you will see all the NSLog statements from that process and be able to see a UITableView in memory with the correct number of objects and so on as you step through the executing code, but what is hard to pick up is you're not looking at the one being presented to the user. So can be tricky to track down. :)
Just remove the code above, implement prepareForSegue:sender: and the universe will return to being a predictable place.
If you add UITableView inside the UIViewController, you need to set the frame size of the UITableView same as the frame size of the view inside the UIViewController, otherwise the tableview size may be 0, cannot display anything.
You can set the frame size if you create the UITableView by storyboard in your case:
- (void)viewDidLoad {
[super viewDidLoad];
// Set tableview delegate and datasource here
menuTableView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
}

How to set up UITableView within a UIViewController created on a .xib file

I have a class like this:
#interface ExerciseLogDetails : UIViewController<UIActionSheetDelegate, UITableViewDelegate, UITableViewDataSource> {
where I am trying to display some elements followed by a UITextView. The UITextView element is created on Interface Builder. When executing this code:
- (void)viewDidLoad {
self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
tableView.dataSource = self;
tableView.delegate = self;
[self.view addSubview:self.tableView];
}
a table shows, but not the one I configured in Interface Builder. It is completely blank and unformatted. How can I access my table and populate it progrmmatically with data?
Thank you!
Several of the tips on this thread helped me create this. I am going to offer some more complete code files in order to help others as well:
Step 1. Drag your UITableView onto your View Controller either in Storyboards or XIBs. In my example I am using a story board.
Step 2: Open your ViewController (in my case its just DefaultViewController) and add the two delegates for the UITableView: UITableViewDelegate and UITableViewDataSource. Also add a simple data source for population and the UITableView IBOutlet.
DefaultViewController.h
#import <UIKit/UIKit.h>
#interface DetailViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
#property (strong, nonatomic) IBOutlet UITableView *tableView;
#property (strong, nonatomic) NSMutableArray *newsArray;
#end
Step 3: Open your implementation file (DefaultViewController.m) and add the following:
#import "DetailViewController.h"
#interface DetailViewController ()
- (void)configureView;
#end
#implementation DetailViewController
#synthesize newsArray;
#synthesize tableView;
#pragma mark - Managing the detail item
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self configureView];
}
- (void)configureView
{
// Update the user interface for the detail item.
self.newsArray = [[NSMutableArray alloc] initWithObjects:#"Hello World",#"Goodbye World", nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// typically you need know which item the user has selected.
// this method allows you to keep track of the selection
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView
editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewCellEditingStyleDelete;
}
// This will tell your UITableView how many rows you wish to have in each section.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.newsArray count];
}
// This will tell your UITableView what data to put in which cells in your table.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifer = #"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifer];
// Using a cell identifier will allow your app to reuse cells as they come and go from the screen.
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifer];
}
// Deciding which data to put into this particular cell.
// If it the first row, the data input will be "Data1" from the array.
NSUInteger row = [indexPath row];
cell.textLabel.text = [self.newsArray objectAtIndex:row];
return cell;
}
#end
Step 4: Goto your Storyboards or XIB and select your UITableView and drag the datasource and delegate outlets onto your DefaultViewController to wire them up. Also you will need to wire up the Referencing Outlet for the UITableView to your IBOutlet tableView object you created in your header file.
Once this is finished you should be able to run it and the sample data will be in place.
I hope this along with the other tips on this thread will help others setup a UITableView from scratch on a ViewController.
If you configured a tableView in IB you shouldn't also create one programmatically, you should create #property (nonatomic, retain) IBOutlet UITableView *tableView; and connect it to the tableView you configured in IB.
Try to set a breakpoint in the tableView's
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
delegate method to see if this method get called.
From Apple UITableView docs:
A UITableView object must have an object that acts as a data source
and an object that acts as a delegate; typically these objects are
either the application delegate or, more frequently, a custom
UITableViewController object. The data source must adopt the
UITableViewDataSource protocol and the delegate must adopt the
UITableViewDelegate protocol. The data source provides information
that UITableView needs to construct tables and manages the data model
when rows of a table are inserted, deleted, or reordered. The delegate
provides the cells used by tables and performs other tasks, such as
managing accessory views and selections.
As u can see if u don't set a dataSource to your tableView, the tableView will not know how and what to display, so nothing will happen.
You can set one by calling tableView.dataSource = self; or in IB drag from your tableView to the file's owner (that is your viewController that must implement the UITableViewDataSource Protocol)
There are two methods in the UITableViewDataSource protocol that your dataSource must implement:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
and
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
If u won't implement those methods u will get a compiler warnings.
You can have more control on how the tableView will look if you implement the UITableViewDelegate protocol - like row/header/footer height, selections and more...
From Apple UITableView docs:
UITableView overrides the layoutSubviews method of UIView so that it
calls reloadData only when you create a new instance of UITableView or
when you assign a new data source. Reloading the table view clears
current state, including the current selection. However, if you
explicitly call reloadData, it clears this state and any subsequent
direct or indirect call to layoutSubviews does not trigger a reload.
ReloadData get called when the tableView is created or when you assign a new dataSource (or when you explicitly call it of course..).
This is when the tableView needs to know what to display (how many sections?, how many rows?, and which cell to display?) - So this is when numberOfRowsInSextion method called.
Like Eyal said, you shouldn't create a UITableView programmatically and in the Interface Builder. Instead, it is much easier to just create one in Interface Builder and assigns it's delegate and datasource properties to File's Owner in IB.
Once you've done this, you don't need to create one programmatically and there's no need for a #property for the tableview.
Instead, you could have your UIViewController's class files look like this:
// YourViewController.h
#import <UIKit/UIKit.h>
#interface YourViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
#property (strong, nonatomic) NSArray *yourData;
#end
Where the NSArray will contain your data that you will enter into the table programmatically. You may use other data classes too like an NSDictionary depending on what data you have and how you want it to sit in the table.
// YourViewController.m
#import "YourViewController.h"
#implementation YourViewController
#synthesize yourData;
- (void)viewDidLoad
{
[super viewDidLoad];
// Here you are creating some data to go in your table by inputting it as an array.
// I just used some basic strings as an example.
NSArray *array = [[NSArray alloc] initWithObjects:#"Data1", #"Data2", #"Data3", nil];
// Copying the array you just created to your data array for use in your table.
self.yourData = array;
}
- (void)viewDidUnload
{
[super viewDidUnload];
self.yourData = nil;
}
#pragma mark Table View Data Source Methods
// This will tell your UITableView how many rows you wish to have in each section.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.yourData count];
}
// This will tell your UITableView what data to put in which cells in your table.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifer = #"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifer];
// Using a cell identifier will allow your app to reuse cells as they come and go from the screen.
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifer];
}
// Deciding which data to put into this particular cell.
// If it the first row, the data input will be "Data1" from the array.
NSUInteger row = [indexPath row];
cell.textLabel.text = [yourData objectAtIndex:row];
return cell;
}
#end
This should just create a simple UITableView with three entries of data that you have entered programmatically.
If you have any problems or questions just post a comment. :)
Hope this helps.

Resources