Populating a TableView in ViewDidAppear - ios

I am trying to do what I thought would be simple, but is seems quite complex.
I am trying to create a leaderboard screen.
I have the following:
NSArray* playerNames
NSArray* playerScores
My leaderboard tab is a viewcontroller. Inside, it has a tableview. The tableview has an outlet.
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#interface LeaderboardViewController : UIViewController
{
}
- (void)viewDidAppear:(BOOL)animated;
- (void) viewWillDisappear:(BOOL)animated;
#property (weak, nonatomic) IBOutlet UITableView *leaderboardTable;
- (SimonGameModel*) model;
#end
When the view did load, I get the above 2 arrays (both of same length) from my model. They correspond to the latest scores.
What I need is for each table cell to tave 2 lables so that I end up with a leaderboard that looks something like this:
Tim 200
John 100
Jack 50
etc...
I have been reading apple's docs for nearly an hour and I am confused as to how to do this.
I created a prototype with the labels I want.
Thanks

-(void)viewDidLoad {
[leaderboardTable setDataSource:self];
[leaderboardTable setDelegate:self];
}
you must create your custom cell in this way:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [playerNames count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"leader";
UITableViewCell *cell = [leaderboardTable dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
UILabel *labelName = [[UILabel alloc] initWhitFrame:CGRectMake(5, 0,160,44);
[labelName setTextAlignment:NSTextAlignmentLeft];
labelName.textColor = [UIColor blackColor];
[cell.contentView addSubView:labelName];
UILabel *labelValue = [[UILabel alloc] initWhitFrame:CGRectMake(165, 0, 150, 44);
[labelValue setTextAlignment:NSTextAlignmentRight];
labelValue.textColor = [UIColor blackColor];
[cell.contentView addSubView:labelValue];
}
labelName.text = [playerNames objectAtIndex:indexPath.row];
labelValue.text = [playerScores objectAtIndex:indexPath.row];
return cell;
}

It sounds like you have not set your LeaderboardViewController as your tableview's dataSource. LeaderboardViewController will have to conform to the UITableViewDataSource protocol:
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableViewDataSource_Protocol/Reference/Reference.html#//apple_ref/doc/uid/TP40006941
Also, remember to register a UITableViewCell xib or class with your tableview.
You will be populating your cells with data from your arrays in - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

Related

Adding custom edit and delete button in UITableViewCell

I have a UITableView which contains the names of all countries.
The user can delete or edit the name of country anytime by taping on the cell.
My UITableView cell initially looks like this:
Now when user taps on it I am changing it like this:
I think I am following a very lame approach.Here is what I did:
Declared globally buttons to add:
UIButton *btnDeleteWithImage,*btnDeleteWithText,*btnEditWithImage,*btnEditWihtText; //buttons
And a NSMutableArray to keep track of indexPath.row
Now in my didSelectMethod I am doing this:
//To change the background
UIView *selectionBackground = [[UIView alloc] init];
selectionBackground.backgroundColor = [UIColor customColor];
cell.selectedBackgroundView = selectionBackground;
// to check which cell is pressed
if([indexPathCollection containsObject:index])
{
[btnDeleteWithImage removeFromSuperview];
[btnDeleteWithText removeFromSuperview];
[btnEditWihtText removeFromSuperview];
[btnEditWithImage removeFromSuperview];
[indexPathCollection removeObject:index];
[cell addSubview:btnDeleteWithImage];
[cell addSubview:btnDeleteWithText];
[cell addSubview:btnEditWithImage];
[cell addSubview:btnEditWihtText];
[indexPathCollection addObject:index];
}
else
{
[cell addSubview:btnDeleteWithImage];
[cell addSubview:btnDeleteWithText];
[cell addSubview:btnEditWithImage];
[cell addSubview:btnEditWihtText];
[indexPathCollection addObject:index];
}
But this is not working good.When I scroll table edit and delete button randomly occurs.
Did someone has better Idea how can achieve this in a very efficient way.
You can achieve this by creating a custom cell with your properties
CustomCell.h
#interface CustomCell : UITableViewCell
#property (nonatomic, strong) UIButton *btnDeleteWithImage;
#property (nonatomic, strong) UIButton *btnDeleteWithText;
#property (nonatomic, strong) UIButton *btnEditWithImage;
#property (nonatomic, strong) UIButton *btnEditWithText;
#end
initialize them in cell's init method keeping them hidden at first or you can do
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *customCellIdentifier = #"customCellIdentifier";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:customCellIdentifier];
if (!cell) {
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:customCellIdentifier];
// or you can initialize and add them to the cell here
}
//here you can modify them accordingly
return cell;
}
then the delegate method can be
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
CustomCell *cell = [tableView cellForRowAtIndexPath:indexPath];
[cell.btnDeleteWithImage setHidden:NO];
[cell.btnEditWithImage setHidden:NO];
}
the simplest way is that do not reuse the cell . & register your custom cell with same indentifire .
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
customCell* cell = [[customCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier:#"indentifire"] ;
// manage your plooting here ..
return cell;
}
hope it works for you.

iOS TableView Referencing outlet

I can not connect referencing outlet to showTableView on storyboard. I can only connect to view .I was trying to show the tableview with some data. Here are the codes that I am using.Please help me.Thank you.
ViewController.h
#interface ViewController : UIViewController<UITableViewDataSource, UITableViewDelegate>
#property(nonatomic, strong) IBOutlet UITableView *showTableView;
ViewController.m
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [jsonResults count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *simpleIdentifier = #"SimpleIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:simpleIdentifier];
}
// Configure the cell...
NSDictionary *appsdict = [jsonResults objectAtIndex:indexPath.row];
NSString *nameString = [appsdict objectForKey:#"name"];
cell.textLabel.text = [appsdict objectForKey:#"name"];
cell.textLabel.textColor = [UIColor whiteColor];
cell.textLabel.font = [UIFont boldSystemFontOfSize:12];
return cell;
}
Make sure you've set your UIViewController's Custom Class to ViewController in the interface so you can properly link its outlets (including showTableView) to ViewController.

Custom Cells are created, but not displayed

So I've used this tutorial to populate a UITableView with custom cells that represent balances. When stepping through the code, I witness the correct amount of cells get created (only 4 with the current test data) and their labels' text set correspondingly.
My problem is when the table is displayed on the screen, only the first row/cell is displayed.
Any insight as to why this could be occurring would be greatly appreciated!
Removed old code.
BalanceCell.h:
#import <UIKit/UIKit.h>
#interface BalanceCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UILabel *nameLabel;
#property (weak, nonatomic) IBOutlet UILabel *amountLabel;
#property (weak, nonatomic) IBOutlet UILabel *modifiedLabel;
#end
EDIT:
My TableView delegate methods are now as follows:
- (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 [_balances count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
BalanceCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[BalanceCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.backgroundColor = [_hex colorWithHexString:_themeColourString];
return cell;
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(BalanceCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
Balance *item = [_balances objectAtIndex:indexPath.row];
cell.nameLabel.textColor = _themeColour;
cell.nameLabel.text = item.name;
cell.amountLabel.textColor = _themeColour;
cell.amountLabel.text = [NSString stringWithFormat:#"%#%#", item.symbol, item.value];
cell.modifiedLabel.textColor = _themeColour;
cell.modifiedLabel.text = [NSString stringWithFormat:#"%#", item.modified];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 94;
}
As #Sebyddd suggested, I now register the NIB in the viewDidLoad method.
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableView registerNib:[UINib nibWithNibName:#"BalanceCell" bundle:nil] forCellReuseIdentifier:#"Cell"];
}
These changes may make my code more correct but still only the first cell is displayed.
If cells are getting created and returned properly I guess height is not being set propery. By default I beleive all cells have a height of 44. If your cell exceeds this height it might not get displayed.
You can tell the tableview to adjust height for every cell using (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath delegate
In that delegate just return your cells height.
EDIT:
You are using dequeueReusableCellWithIdentifier: which will return A UITableViewCell object with the associated identifier or nil if no such object exists in the reusable-cell queue.
Instead use dequeueReusableCellWithIdentifier:forIndexPath: which will return A UITableViewCell object with the associated reuse identifier. This method always returns a valid cell.
You need to register the nib/class for that custom cell in viewDidLoad
Try this:
if (cell == nil) {
[tableView registerNib:[UINib nibWithNibName:#"BalanceCell" bundle:nil] forCellReuseIdentifier:#"Cell"];
cell = [[BalanceCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
}
Use this tuto : http://www.appcoda.com/uitableview-tutorial-storyboard-xcode5/ , your tuto is a bit outdated, and hard to follow !

Set delegate to an object

This is the first time im trying to set a UITableView delegate/datasource to an instance of an object.
I have a UIView managed by a class called hMain, and a UITableView inside of main managed by an instance of a class called vTable.
hMain.h:
#interface hMain : UIViewController
#property (strong, nonatomic) IBOutlet vTable *voteTbl;
#end
hMain.m:
- (void)viewDidLoad
{
[super viewDidLoad];
voteTbl = [[vTable alloc]init];
[self.voteTbl setDelegate:voteTbl];
[self.voteTbl setDataSource:voteTbl];
}
vTable.h:
#interface vTable : UITableView <UITableViewDelegate , UITableViewDataSource>
#end
vTable.M:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 5;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [UITableViewCell configureFlatCellWithColor:[UIColor greenSeaColor] selectedColor:[UIColor wetAsphaltColor] reuseIdentifier:CellIdentifier inTableView:(UITableView *)tableView];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
[cell configureFlatCellWithColor:[UIColor greenSeaColor] selectedColor:[UIColor wetAsphaltColor]];
}
cell.textLabel.text = #"Hello there!";
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"Row pressed!!");
}
This is really my first time straying away from IB and doing things programatically so im not sure im settings delegates and things correctly. This is also my first attempt and setting a delegate/datasource outside of self.
My problem is the table is coming out blank every time.
What is vTable? Looks like you have a "voteTable" class (BTW: classes should start with an uppercase char, instance variables should start with lowercase). Anyhow, looks like your main problem is you forgot to add the table as a subview and set its frame. eg:
self.voteTbl = [[VoteTable alloc] init];
self.voteTbl.delegate = self;
self.voteTbl.dataSource = self;
self.voteTbl.frame = self.view.bounds;
[self.view addSubView:self.voteTbl];

How can i use custom UITableViewCell and UITableView in same xib

I want to use a custom UITableviewCell with UITableView in same xib without creating a UITableViewCell class?
As you can see bellow i set the identifier for UITableViewCell and used it like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CustomIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
}
But Not Working?
Add a UITableViewCell *customCell property to your view controller (for example, your file ShowUsers.h)...
#property (nonatomic, strong) IBOutlet UITableViewCell *customCell;
and connect it to the custom cell in your xib. Then use the following code in cellForRow (for example, your file ShowUsers.m) :
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:#"NibName" owner:self options:nil];
cell = self.customCell;
self.customCell = nil;
}
Yes you can do as following code
Under ViewDidLoad or ViewWillAppear
label1Array=[NSMutableArray arrayWithObjects:#"A",#"B",nil];
label2Array=[NSMutableArray arrayWithObjects:#"C",#"D",nil];
label3Array=[NSMutableArray arrayWithObjects:#"E",#"F",nil];
UITableViewDelegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"aCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
UILabel *label1=[[UILabel alloc]init];
label1.frame=CGRectMake(0,0,40,40);
label1.text=[label1Array objectAtIndex:indexPath.row];
................
[cell.contentView addSubView: label1];
UILabel *label2=[[UILabel alloc]init];
label2.frame=CGRectMake(50,0,40,40);
label2.text=[label2Array objectAtIndex:indexPath.row];
[cell.contentView addSubView: label2];
UILabel *label3=[[UILabel alloc]init];
label3.frame=CGRectMake(100,0,40,40);
label3.text=[label3Array objectAtIndex:indexPath.row];
[cell.contentView addSubView: label3];
}
Hope this Helps !!!
See..You can do like this. Here you are adding two UITableViewCell in one TableView using XIB.
In Class.h file :-
Declare one mutable array for number of cells.
{
NSMutableArray * sectionRows;
}
#property (nonatomic,retain) IBOutlet UITableViewCell *addTvc1;
#property (nonatomic,retain) IBOutlet UITableViewCell *addTvc2;
In Class.m :-
#synthesize addTvc1, addTvc2;
- (void)viewDidLoad
{
[super viewDidLoad];
sectionRows = [[NSMutableArray alloc] init];
[sectionRows addObject:[[NSMutableArray alloc]
initWithObjects:addTvc1, nil]];
[sectionRows addObject:[[NSMutableArray alloc]
initWithObjects:addTvc2, nil]];
}
In UITableViewDelegate Method -
Add This -
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [sectionRows count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
(NSInteger)section
{
return [[sectionRows objectAtIndex:section] count];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath
{
return [[sectionRows objectAtIndex:indexPath.section]
objectAtIndex:indexPath.row];
}
Along with code, In Class's XIB drop and drag two UITableViewCell which should be outside from the view and add those cells with Files Owner.
It will work perfectly. Here no need to create one separate custom UITableViewCell class.

Resources