I have been implementing a app with sectioned UITableView. In the tableview, I used a array, called sections, to store different classes array and show them in different sections. On the other hand, I also used a array, called headers, to store section headers' name. For example, in the "weekday" section, there are seven words, Sunday to Saturday, in the tableViewCell under this section. In the MainViewController:
-(void)viewDidLoad
{
[super viewDidLoad];
NSMutableArray *weekday=[[NSMutableArray alloc]init];
NSMutableArray *traffic=[[NSMutableArray alloc]init];
for (NSArray *sec_ary in listData) {
NSString *class=[[sec_ary valueForKey:#"vocabulary_list"]valueForKey:#"Class"];
if ([class isEqualToString:#"WEEKDAY"]) {
[weekday addObject:[[sec_ary valueForKey:#"vocabulary_list"]valueForKey:#"Vocabulary"]];
}else if ([class isEqualToString:#"TRAFFIC TOOLS"]){
[traffic addObject:[[sec_ary valueForKey:#"vocabulary_list"]valueForKey:#"Vocabulary"]];
}
sections=[[NSArray alloc ]initWithObjects:weekday,traffic,nil];
headers=[[NSArray alloc]initWithObjects:#"WEEKDAY",#"TRAFFIC TOOLS",nil];
}
In this App, I also implemented the navigation controller, which can bring user to view detail information in the didSelectRowAtIndexPath method. The codes are following
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
ContentViewController *content= [[ContentViewController alloc] initwithIndexPath:indexPath];
[delegate.navController1 pushViewController:content animated:YES];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *TableIdentifier = #"tableidentifier"; /
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TableIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:TableIdentifier] autorelease];
}
cell.textLabel.text = (NSString*)[[self.sections objectAtIndex:indexPath.section]objectAtIndex:indexPath.row];
cell.textLabel.font = [UIFont boldSystemFontOfSize:15];
return cell;
}
In the ContentViewController:
-(void)viewDidLoad{
[super viewDidLoad];
AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];
NSDictionary *voc_list=[delegate.vcblr objectAtIndex:index.row];
//extracting the voc_list dictionary to show infomation.....
}
I am wondering why each section will load the information from beginning in the voc_list. That is to say, the tableViewCell do not respond to the right detail content. Could anyone provide me with ideas to resolve it?
I am wondering why each section will load the information from beginning in the voc_list.
Because the code of your viewDidLoad method ignores index.section, paying attention to index.row alone. You need to decide on the index that you pass to delegate.vcblr based on both the section and the row; the exact calculation depends on the structure of your data, i.e. how many rows you have in each section.
Note : Using AppDelegate to share data among view controllers is not a good idea. Consider separating out your data in a separate model class, and make that class a singleton.
Related
I'm trying to reuse cell created in my storyboard,
I'm using this code:
MyTableView * mytableview;
UIStoryboard *sb = [UIStoryboard storyboardWithName:#"MainStoryboard" bundle:nil];
mytableview = [sb instantiateViewControllerWithIdentifier:#"myTable"];
AlertCell *cell;
cell = [mytableview.tableView dequeueReusableCellWithIdentifier:#"alertCell"];
cell.message.text = #"some text";
return cell;
I get this error:
[__NSArrayM objectForKeyedSubscript:]: unrecognized selector sent to instance 0xe02b7d0
this line eventually generates the error:
[mytableview.tableView dequeueReusableCellWithIdentifier:#"alertCell"];
The table view when using the cell is programaticlly created.
Everything i wanted works! but i got the errors in the log anyway
Thanks a lot!
You cannot create the table view when the cell is created.
You have to create the table view in a method that i called when the view controller is created, such as viewDidLoad.
Then in the cell method use the tableView pointer that is included in the method.
Also, the error actually indicates a problem with your datasource as well.
There are so many apparent knowledge gaps, maybe the best way is to read through the Table View Programming Guide.
I didn't exactly understand when you are creating table. You should not instantiate at the same time. Why you needed to call this line?
mytableview = [sb instantiateViewControllerWithIdentifier:#"myTable"];
If you want to use tableview, just create it normally and add it to your viewcontroller instead of using above line of code in viewDidLoad.
UITableView *tableView = [[UITableView alloc]initWithFrame:tableFrame style:UITableViewStylePlain];
tableView.rowHeight = 45;
[self.view addSubview:tableView];
tableView.delegate = self;
tableView.datasource = self;
Implement tableview's data source and delegate methods. And in cellForRowAtIndexPath::
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"newFriendCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"newFriendCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
//do your stuff
return cell;
}
I am programmatically creating a tableview in objective c. How can I make the cells static programmatically?
Thanks
Making cells static programmatically doesn't really make sense. Static cells are basically only for Interface Builder and requires the entire TableView to be static. They allow you to drag UILables, UITextFields, UIImageViews, etc. right into cells and have it show up just how it looks in Xcode when the app is run.
However, your cells can be "static" programmatically by not using an outside data source and hardcoding everything, which is usually going to be kind of messy and generally a poor idea.
I suggest making a new UITableViewController with a .xib and customizing it from there if you want "static" cells. Otherwise, just hardcode all your values and it's basically the same thing, but is probably poor design if it can be avoided.
By using a distinct cell identifier for each one you will get it. You could use something like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellIdentifier = [NSString stringWithFormat:#"s%i-r%i", indexPath.section, indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
//you can customize your cell here because it will be used just for one row.
}
return cell;
}
You could also do it the old fashioned and just create the cell the way you want depending on the NSIndexPath, this works with Static Cell TVC's and regular table views (don't forget to return the proper number of sections and rows in their datasource methods):
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
switch indexPath.row {
case 0:
// First cell, setup the way you want
case 1:
// Second cell, setup the way you want
}
// return the customized cell
return cell;
}
I you want to create cells structure for example for a settings screen or something like that and you maybe need just to modify some cells content but not their number or sections structure you can overload method of your UITableViewController subclass like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *aCell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
// Configure the cell...
if ([aCell.reuseIdentifier isEqualToString:#"someIdentifier"]){
//some configuration block
}
else if ([aCell.reuseIdentifier isEqualToString:#"someOtherIdentifier"]) {
//other configuration block
}
return aCell;
}
But you can make it in a better way with a little bit more code;
1) In the begining of your .m file add typedef:
typedef void(^IDPCellConfigurationBlock)(UITableViewCell *aCell);
2) add cellConfigurations property to your TablviewControllerSubclass extention:
#interface IPDSettingsTableViewController ()
#property (nonatomic, strong) NSDictionary *cellConfigurations;
#property (nonatomic) id dataModel;
#end
3) Modify your static cells of TableviewController subclass in storyboard or xib
and add unique cellReuseIdentifier for each cell you want to modify programmatically
4) In your viewDidLoad method setup cellsConfiguration blocks:
- (void)viewDidLoad
{
[super viewDidLoad];
[self SetupCellsConfigurationBlocks];
}
- (void)SetupCellsConfigurationBlocks
{
//Store configurations code for each cell reuse identifier
NSMutableDictionary *cellsConfigurationBlocks = [NSMutableDictionary new];
//store cells configurations for a different cells identifiers
cellsConfigurationBlocks[#"someCellIdentifier"] = ^(UITableViewCell *aCell){
aCell.backgroundColor = [UIColor orangeColor];
};
cellsConfigurationBlocks[#"otherCellIdentifier"] = ^(UITableViewCell *aCell){
aCell.imageView.image = [UIImage imageNamed:#"some image name"];
};
//use waek reference to self to avoid memory leaks
__weak typeof (self) weakSelf = self;
cellsConfigurationBlocks[#"nextCellIdentifier"] = ^(UITableViewCell *aCell){
//You can even use your data model to configure cell
aCell.textLabel.textColor = [[weakSelf.dataModel someProperty] isEqual:#YES] ? [UIColor purpleColor] : [UIColor yellowColor];
aCell.textLabel.text = [weakSelf.dataModel someOtherProperty];
};
weakSelf.cellConfigurations = [cellsConfigurationBlocks copy];
}
5) overload tableView:cellForRowAtIndexPath method like this:
#pragma mark - Table view data source
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *aCell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
// configure cell
[self configureCell:aCell withConfigurationBlock:self.cellConfigurations[aCell.reuseIdentifier]];
return aCell;
}
- (void)configureCell:(UITableViewCell *)aCell withConfigurationBlock:(IDPCellConfigurationBlock)configureCellBlock
{
if (configureCellBlock){
configureCellBlock(aCell);
}
}
It is pretty common to want to build a simple table to use as a menu or form, but using the built in API with the datasource and delegate callbacks don't make it easy to write or maintain. You may need to dynamically add/remove/update some cells, so using Storyboards by itself won't work.
I put together MEDeclarativeTable to programmatically build small tables. It provides the datasource and delegate for UITableView. We end up with an API where we provide instances of sections and rows instead of implementing datasource and delegate methods.
I have two UITableViewControllers. In the first UITableView, once a user selects a cell, a new UITableViewController is pushed. I have set both UITableViews to "Grouped" in IB. However, when the second UITableViewController is pushed, it appears as a "Plain" UITableView. Is there a way to fix this?
Just as a sanity check, I changed the code so that the second UITableViewController is pushed not from the first UITableViewController, and it does appear to be "Grouped". Is there a reason this is happening?
Code From UITableViewController that is pushing second UITableViewController:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if ([cell.text isEqualToString:#"Long Term Disability"]) {
LongDisabilityTableView *ldvc = [LongDisabilityTableView alloc];
[self.navigationController pushViewController:ldvc animated:YES];
}
if ([cell.textLabel.text isEqualToString:#"Short Term Disability"]) {
ShortDisabilityTableView *sdvc = [ShortDisabilityTableView alloc];
[self.navigationController pushViewController:sdvc animated:YES];
}
}
If you are pushing to a UITableViewController, you can force the table to be grouped by doing one of the following:
Init
MyTableController *grouped = [[MyTableController alloc] initWithStyle:UITableViewStyleGrouped];
Super
This needs to be added to a UITableViewController.
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:UITableViewStyleGrouped]; /* This is where the magic happens */
if (self) {
self.title = #"My Grouped Table";
}
return self;
}
Double Check
Make sure that you are not placing your UITableView on a UIViewController.
Make sure that you are calling the correct controller in your code (from didSelectRowAtIndexPath:)
Update, added after code
Well there's one reason right there, you aren't using init. See my first example above.
You should also change your code to this:
/* This assumes that your Long Term Disability cell is at index 0
and that your Short Term Disability cell is at index 1.
*/
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
switch ( indexPath.row )
{
case 0: /* #"Long Term Disability" */
LongDisabilityTableView *ldvc = [[LongDisabilityTableView alloc] initWithStyle:UITableViewStyleGrouped];
[self.navigationController pushViewController:ldvc animated:YES];
break;
case 1: /* #"Short Term Disability" */
ShortDisabilityTableView *sdvc = [[ShortDisabilityTableView alloc] initWithStyle:UITableViewStyleGrouped];
[self.navigationController pushViewController:sdvc animated:YES];
break;
}
}
So I've been given an assignment in my Mobile apps class: make a color game app for the iphone.(The description of how to game works is at the top of the pasted viewcontroller.h file below.)
I'm very new to Objective-C and cocoa, but have managed to troubleshoot and fix a lot of things in this app. The problem I have right now is that I don't know how to properly initialize and send UITableViewCells to the view. I'm confused because all of the tutorials I've found online use datasource methods to change different attributes of the UITableView and the cells as well. I'm not sure how these methods will interact with the controls I've already placed. I'm confused because I added them by the storyboard file, not by defining tableview attributes with datasource code.
My immediate issue is that my program won't display the proper text to the cells textlabel and detailtextlabel.
I've looked everywhere online for UITableView and UITableViewCell tutorials, but they are all from years ago and I'm not sure if the advent of the storyboard has changed the way I would treat these controls.
All of the code I've written is either in the viewcontroller.m or viewcontroller.h files.
The method within ViewController.m file, that should call the cell and display text and detail text:
-(IBAction)enterClicked
{
//On enter- send instance colors to the colorTable row[i], perform comparisons and append the resulting symbols to the instanceResults String. Send instanceResults string to the resultTable row[i]. When game counter reaches 6, gameOver. If on comparisons check, the instanceColors are the same as the gameColors, then the player wins.
[self checkForLoss];
if(!self.gameOver)
{
resultOfGuess = [self comparePlayerInputToGameColors:guessColors];
[listOfGuesses addObject:guessColors];
[listOfOutcomes addObject:resultOfGuess];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_numberOfTurnsPlayed inSection:0];
UITableViewCell *thisCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
thisCell.textLabel.text = [self.listOfGuesses lastObject];
thisCell.detailTextLabel.text = [self.listOfOutcomes lastObject];
[guessColors setString:#""];
if([self checkForWin:resultOfGuess])
[UpdateLabel setText:#"You have won!"];
else
[UpdateLabel setText:#""];
self.colorCounter = 0;
self.isStepOne = YES;
_numberOfTurnsPlayed++;
}
else
{
if([self checkForLoss])
[UpdateLabel setText:#"You have lost!"];
}
}
The UITableView DataSource Methods I've called at the bottom of the viewcontroller.m file:
#pragma mark - UITableViewDataSource protocol
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
if(section == 0)
return #"Guesses: Results:";
return 0;
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 6;
}
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
}
return cell;
}
So my questions are: Can I change a control's properties with datasource methods, if I created the controls through the storyboard? How do I properly display the text in a uitableview's cells?
Edit/update: Thank you, I've used your advice jrturton, but now I've found something peculiar that may be the source of my problems. in my viewController.h file I've changed my header from
ViewController: UIViewController to ViewController: UITableViewController
Thinking that the datasource methods I call within the viewcontroller files have to be able to call the same methods and properties of the class that I call in the header-- Also, I see this done in other UITableView tutorial files.
The problem is that when I change the header to read-- ViewController: UITableViewController -- and I try to compile, I get this error:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UITableViewController loadView] loaded the "2-view-3" nib but didn't get a UITableView.'
It compiles fine if I use just :UIViewController in the header file though.
Any ideas?
Further update: I''ve noticed within my storyboard that the only available ViewController object is a UIViewController object, while in the other tutorial files I've seen, this ViewController object is a UITableViewController object. I imagine this is my problem, but I can't seem to switch my UIViewController object to a UITableViewController. All I can do is create a new one, which isn't what I want, I imagine.
Your action method should update the data model (which I think it does, since it changes your listOfGuesses array). You then need to let your table view know that you have added or updated rows so that it can re-load them for you - check the UITableView documentation for reloading data or specific rows.
Creating a cell outside of the datasource methods isn't going to let that cell appear in your table.
At the moment I'm guessing you have 6 empty cells in your table view? You need to populate the text and detail labels in your cellForRowAtIndexPath method. The difference now there are storyboards is that you don't need to do the if (cell == nil) bit, as long as you have set the re-use identifier in your storyboard prototype cell then it will do all that for you. So your cellForRowAtIndexPath method can be reduced to:
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
// This will dequeue or create a new cell based on the prototype in your storyboard
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
// Put your actual configuration here based on your model array
cell.textLabel.text = #"Hello";
return cell;
}
Further hints (this is homework so I'm not giving full samples)
'indexPath.row` in the above method will give you the index from your model array that the cell refers to
You have defined the table as having 6 rows, but you are adding items to your model arrays as you go - so when the table asks for row 5, and your model only has 3 entries, you need to deal with this. Consider changing the number of rows in the table dynamically and using table view methods to indicate that new rows have been added. Again, see the UITableView documentation for this.
Typically the text is set in each cell by accessing the setText property:
[[cell textLabel] setText:#"static string"];
or
[[cell textLabel] setText:someNSString];
or with .dot notation
cell.textLabel.text = someNSString;
return cell;
BTW this is done in the method:
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:
I am trying to populate a TableView situated within a UIViewController with a collection of objects when a button is clicked.
The problem is that cellForRowAtIndexPath seems to be expecting 'votes' to be an instantiated object, which it isn't until the button is pressed.
I'm not sure I'm going about this the correct way and would appreciate any assistance anybody could give me.
I have specified the delegate and datasource as follows:
#interface MyViewController : UIViewController<UITableViewDelegate, UITableViewDataSource>
I have completed my implementation of numberOfRowsInSection as follows:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.votes count];
}
I have completed my implementation of cellForRowAtIndexPath as follows:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Votes";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the region cell
CandidatePhrase *phrase = [self.votes objectAtIndex:indexPath.row];
cell.textLabel.text = phrase.phrase;
return cell;
}
On button press I'm loading an array with a list of objects
_votes = [[NSArray alloc] initWithObjects:myCandidatePhrase.votes, nil];
I'm just now clear on how the table will bind each time I press the button.
Here's the error I'm currently getting, presumably because the votes array hasn't been instantiated?
2011-12-09 22:34:48.979 MyApp[3809:fb03] -[NSObject tableView:numberOfRowsInSection:]: unrecognized selector sent to instance 0x6b49b20
The tableView instance (not the view controller) is going to call its delegate methods as soon as it is instantiated and whenever it is informed of a change to the table view. So it doesn't matter if votes is instantiated or not for the delegate method to be called.
However, if you want it to know that there are no rows when votes has not been instantiated, try this
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (votes != nil)
return [self.votes count];
else
return 0;
}
Once you have instantiated votes, you want to call reloadData on your tableView.
Don't forget to add your view controller as the delegate for the tableView, if it is not already.