How to show different view controller based on RowSelected in Tableviewcell? - ios

I am new to iPhone Development and trying to create a small application(Recipe list) with multiple views. When the user selects one of the rows in tablecell, I would like to call a new view. For Instance, the menu card with items mushroom, pasta,steak must call another view with detailed recipe.
I have used UITableViewController to display a list of items with Accessory. These items are dynamically populated from a NSArray. When the user taps on one of the rows in the table, it should take him to a view controller based on the Row Selection. I know I have to implement tableView:didSelectRowAtIndexPath: function to call the appropriate view.
But I am not able to proceed. I read about Segue in storyboards, but even that seems a bit confusing for me.
I would really appreciate if someone solves my query. Here is my code.
RecipeViewController.h
#import "RecipeViewController.h"
#import "Recipe.h"
#interface RecipeViewController ()
#end
#implementation RecipeViewController
{
NSArray *recipes; //Recipe Array
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.title = #"Hotel";
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:#"Back" style:UIBarButtonItemStyleBordered target:nil action:nil];
[[self navigationItem] setBackBarButtonItem:backButton];
// Create recipe array for main screen.
Recipe *recipe1 = [Recipe new];
recipe1.headline = #"Mushroom";
recipe1.description = #"description";
recipe1.imageFile = #"mushroom.jpg";
Recipe *recipe2 = [Recipe new];
recipe2.headline = #"pasta";
recipe2.description = #"Pasta description";
recipe2.imageFile = #"pasta.jpg";
Recipe *recipe3 = [Recipe new];
recipe3.headline = #"Steak";
recipe3.description = #"Steak description";
recipe3.imageFile = #"steak.jpg";
recipes = [NSArray arrayWithObjects:recipe1, recipe2, recipe3,nil];
// Remove table cell separator
[self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
// Assign custom backgroud for the view
self.parentViewController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"welcome_screen"]];
self.tableView.backgroundColor = [UIColor clearColor];
// Add padding to the top of the table view
UIEdgeInsets inset = UIEdgeInsetsMake(5, 0, 0, 0);
self.tableView.contentInset = inset;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#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 recipes.count;
}
- (UIImage *)cellBackgroundForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger rowCount = [self tableView:[self tableView] numberOfRowsInSection:0];
NSInteger rowIndex = indexPath.row;
UIImage *background = nil;
if (rowIndex == 0) {
background = [UIImage imageNamed:#"cell_top.png"];
} else if (rowIndex == rowCount - 1) {
background = [UIImage imageNamed:#"cell_bottom.png"];
} else {
background = [UIImage imageNamed:#"cell_middle.png"];
}
return background;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Display recipe in the table cell
Recipe *recipe = [recipes objectAtIndex:indexPath.row];
UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
recipeImageView.image = [UIImage imageNamed:recipe.imageFile];
UILabel *recipeNameLabel = (UILabel *)[cell viewWithTag:101];
recipeNameLabel.text = recipe.headline;
UILabel *recipeDetailLabel = (UILabel *)[cell viewWithTag:102];
recipeDetailLabel.text = recipe.description;
// Assign our own background image for the cell
UIImage *background = [self cellBackgroundForRowAtIndexPath:indexPath];
UIImageView *cellBackgroundView = [[UIImageView alloc] initWithImage:background];
cellBackgroundView.image = background;
cell.backgroundView = cellBackgroundView;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
CampusViewController *campusViewController;
WhoViewController *whoViewController;
switch (indexPath.row)
{
case 0:
campusViewController=[[CampusViewController alloc] init];
[[self navigationController] pushViewController:campusViewController animated:YES];
break;
case 1:
whoViewController=[[WhoViewController alloc] init]; // not released as ARC is included in the project
[[self navigationController] pushViewController:whoViewController animated:YES];
break;
case 2:
break;
case 3:
break;
default:
break;
}
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"ShowDetails"]) {
RecipeViewController *detailViewController = [segue destinationViewController];
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
/* NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
detailViewController.data = [self.dataController objectInListAtIndex:indexPath.row];
*/
}
}
#end
// Recipe.h
#import <Foundation/Foundation.h>
#interface Recipe : NSObject
#property (nonatomic, strong) NSString *headline; // name of recipe
#property (nonatomic, strong) NSString *description; // recipe detail
#property (nonatomic, strong) NSString *imageFile; // image filename of recipe
#end

Have you read any tutorials on how to do this? This is a very basic question and there are a lot of posts about this out there.
I'll only give you an explanation on how to do it but you will have to code it yourself.
The standard way we go about an application that shows the user different view controllers based on the selection of a UITableViewCell is by using a UINavigatorController. This controller gives you the methods:
– pushViewController:animated:
– popViewControllerAnimated:
... among others. With these two methods you can go back and forth between view controllers, which is what you want to do. So you have to give your navigator controller the table view controller that you already have. You can do that by using UINavigatorController's method – initWithRootViewController:
A little example of what your – tableView:willSelectRowAtIndexPath: might look like is:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UIViewController *myViewController = [[UIViewController alloc] initWithNibName:#"YourNibName" bundle:nil];
self.navigationController pushViewController:[myViewController autorelease] animated:YES];
}
Hope this helps!
Further reading:
UINavigationController tutorial Ray Wenderlich
UINavigationController tutorial Techotopia

Related

List not being populated from other view

I have a view controller where the user can populate an item. Upon exiting the view that object should be saved, and loaded by the previous view which contains a list of all these objects. My NSLog shows that the object is being saved, but I can't get it to appear in the list view.
Code for both controllers is below. Thanks
List Controller
#import "ItemsViewController.h"
#import "Calculation.h"
#import "CalculationItemStore.h"
#import "CalculationDetailViewController.h"
#interface ItemsViewController()
#property UISegmentedControl *segment;
#end
#implementation ItemsViewController
- (instancetype)init
{
// Call the superclass's designated initializer
self = [super initWithStyle:UITableViewStylePlain];
if (self) {
UINavigationItem *navItem = self.navigationItem;
navItem.title = #"MACS";
// Create a new bar button item that will send
// addNewItem: to CalculationsViewController
UIBarButtonItem *bbi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self
action:#selector(addNewItem:)];
// Set this bar button item as the right item in the navigationItem
navItem.rightBarButtonItem = bbi;
navItem.leftBarButtonItem = self.editButtonItem;
}
return self;
}
- (instancetype)initWithStyle:(UITableViewStyle)style
{
return [self init];
}
- (void)viewDidLoad
{
self.segment = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:#"Publication", #"About", nil]];
self.tableView.tableHeaderView = _segment;
[_segment addTarget:self action:#selector(segmentPressed:) forControlEvents:UIControlEventValueChanged];
[self.tableView registerClass:[UITableViewCell class]
forCellReuseIdentifier:#"UITableViewCell"];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.tableView reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[[CalculationItemStore sharedStore] allCalculations] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Get a new or recycled cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"UITableViewCell" forIndexPath:indexPath];
// Set the text on the cell with the description of the item
// that is at the nth index of items, where n = row this cell
// will appear in on the tableview
NSArray *items = [[CalculationItemStore sharedStore] allCalculations];
Calculation *item = items[indexPath.row];
cell.textLabel.text = item.title;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
CalculationDetailViewController *detailViewController = [[CalculationDetailViewController alloc] init];
NSArray *items = [[CalculationItemStore sharedStore] allCalculations];
Calculation *selectedItem = items[indexPath.row];
// Give detail view controller a pointer to the item object in row
detailViewController.calculation = selectedItem;
// Push it onto the top of the navigation controller's stack
[self.navigationController pushViewController:detailViewController
animated:YES];
}
- (void) tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
// If the table view is asking to commit a delete command...
if (editingStyle == UITableViewCellEditingStyleDelete) {
NSArray *items = [[CalculationItemStore sharedStore] allCalculations];
Calculation *item = items[indexPath.row];
[[CalculationItemStore sharedStore] removeItem:item];
// Also remove that row from the table view with an animation
[tableView deleteRowsAtIndexPaths:#[indexPath]
withRowAnimation:UITableViewRowAnimationFade];
}
}
- (void) tableView:(UITableView *)tableView
moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath
toIndexPath:(NSIndexPath *)destinationIndexPath
{
[[CalculationItemStore sharedStore] moveItemAtIndex:sourceIndexPath.row
toIndex:destinationIndexPath.row];
}
- (void)segmentPressed:(id)sender {
if (_segment.selectedSegmentIndex ==0) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"http://ferm.forestry.oregonstate.edu/facstaff/leshchinsky-ben"]];
}else if(_segment.selectedSegmentIndex ==1){
UIImageView *imageView = [[UIImageView alloc] initWithFrame: CGRectMake(0, 0, 320, 480)];
imageView.backgroundColor = [UIColor redColor];
[imageView setImage: [UIImage imageNamed:#"MACSLoad#2x.png"]];
[self.view addSubview: imageView];
sleep(5);
imageView.hidden = YES;
}
}
- (IBAction)addNewItem:(id)sender
{
// Create a new Calculation and add it to the store
Calculation *newItem = [[CalculationItemStore sharedStore] createCalculation];
CalculationDetailViewController *detailViewController = [[CalculationDetailViewController alloc]initForNewItem:YES];
detailViewController.calculation = newItem;
detailViewController.dismissBlock = ^{
[self.tableView reloadData];
};
UINavigationController *navController = [[UINavigationController alloc]initWithRootViewController:detailViewController];
navController.modalPresentationStyle = UIModalPresentationFullScreen;
// [self presentViewController:navController animated:YES completion:NULL];
[self.navigationController pushViewController:detailViewController animated:YES];
}
#end
Item controller save method
-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
//clear responder
[self.view endEditing:YES];
//save changes
BOOL success = [[CalculationItemStore sharedStore]saveChanges];
if(success){
NSLog(#"Saved all calcs");
}else{
NSLog(#"failure saving");
}
}
I think the issue is that by the time the table reloadData is called on the first controller, the second one is not done loading. You could notify the first VC to reload the data once the second one is done saving It can be notified using
create a delegate on the second one or
using notifications
Let me know if you need more details on how to do this!
Looks like there is also an issue with the object creation.
your calculation elements are not getting created properly. When you are ready to save.. look at the contents of self.privateItems. They values filled in are nil. You will need to instantiate the Strings properly.
engineerName needs to be alloc'd and other strings as well.
and when user hits Done, the values from the text boxes need to be set to the your data model.

How do I get from one table view to the other

I'm a beginner at this and I'm trying to create an app in which you can select from several options. Therefore, I have a table view. Depending on which cell was tapped, another screen should appear with a second table view where I can checkmark things. Right now, I have one view controller in which I'm creating the first table view. How do I get to the second table view and how does it display the other array. Here is the code so far...
#interface ViewController (){
NSArray *genres;
NSArray *images;
NSMutableArray *array1;
NSMutableArray *array2;
NSMutableArray *array3;
}
#end
#implementation ViewController
#synthesize tableView;
(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.title = #"Genres";
// Arrays must be in same order for image and title correspondance
genres = [[NSArray alloc] initWithObjects:
#"a1",
#"a2",
#"a3",
nil];
images = [[NSArray alloc] initWithObjects:
#"1.jpeg",
#"2.jpeg",
#"3.jpeg",
nil];
array1 = [[NSMutableArray alloc] initWithObjects:
#"1.1",
#"1.2",
#"1.3",
nil];
array2 = [[NSMutableArray alloc] initWithObjects:
#"2.1",
#"2.2",
#"2.3",
nil];
array3 = [[NSMutableArray alloc] initWithObjects:
#"3.1",
#"3.2",
#"3.3",
nil];
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger) numberOfSectionsInTableView:(UITableView *) tableView{
return 1;
}
- (NSInteger) tableView:(UITableView *) tableView numberOfRowsInSection:(NSInteger)section{
return genres.count;
}
//Customize the apperance 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];
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
}
//Configure Cell
cell.textLabel.text = [genres objectAtIndex:indexPath.row];
cell.imageView.image = [UIImage imageNamed:[images objectAtIndex:indexPath.row]];
return cell;
}
#pragma mark -
#pragma mark Table view delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSArray *selectedArray = [[NSArray alloc] init];
switch (indexPath.row) {
case 0:
selectedArray = array1;
break;
case 1:
selectedArray = array2;
break;
case 2:
selectedArray = array3;
break;
default:
break;
}
}
You can 1) create second view controller from code and set array like argument or 2) use segue interface:
Try to follow this complete answer:
https://stackoverflow.com/a/9736559/2429147
Also this link may be helpful regarding to work with segues and storyboards:
http://agilewarrior.wordpress.com/2012/01/25/how-segue-in-ios-and-pass-data-from-one-viewcontroller-to-another/

Table View Cell not displaying when Running iOS Simulator

I'm trying to create a table but none of the data I inputted is displaying when I run the simulator. I'm trying to create a simple address book application and So far, here is what I did:
From the empty story board, I added a View Controller from the Object Library then inside the view controller, I added a Table View. Then I embedded the View Controller inside a Navigation Controller. I also added another View Controller in the end to act as a "Details" View.
Inside my viewController.h I added the following code:
#property (strong, nonatomic) NSArray *contact;
#property (strong, nonatomic) NSArray *contactDetails;
#property (nonatomic) NSInteger selectedIndex;
contact is to act as the array that shows all the contacts within the phonebook (This is what I'm having trouble displaying)
contactDetails shows once a user selects a contact.
selectedIndex is my way of telling the application which contact has been selected.
Inside my viewController.m I added the following code:
#import "HWViewController.h"
#interface HWViewController ()
#end
#implementation HWViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.tableView registerClass: [UITableViewCell class] forCellReuseIdentifier:#"Cell"];
self.contact = [[NSArray alloc] initWithArray: [NSArray arrayWithObjects:#"Joe", #"Simon", nil]];
self.contactDetails = [[NSArray alloc] initWithArray: [NSArray arrayWithObjects: #"+689171898057", #"+689173104153", nil]];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (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 self.contact.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
if(cell==nil){
cell = [[[NSBundle mainBundle] loadNibNamed:#"SampleCell" owner:nil options:nil] objectAtIndex:0];
}
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 100, 30)];
label.text = [self.contact objectAtIndex:indexPath.row];
[cell.contentView addSubview:label];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
self.selectedIndex = indexPath.row;
[self performSegueWithIdentifier:#"TranslationSegue" sender:self];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
UIViewController *vc = [segue destinationViewController];
UILabel *details = [[UILabel alloc] initWithFrame:CGRectMake(10, 80, 250, 32)];
details.text = [self.contactDetails objectAtIndex:((HWViewController*)sender).selectedIndex];
[vc.view addSubview:details];
}
#end
After that, I ran the simulation and I get nothing showing up on the table.
you have no cell in the tableview. so add tableview cell in your storyboard
http://www.appcoda.com/customize-table-view-cells-for-uitableview/
Add this in your viewController.h :
#property(nonatomic, strong) IBOUTLET UITableView * TableView;
And then link this outlet to your tableview and then try it out.
And there is no cell in your table view because the prototype cell will be set to zero by default. Now select the tableview go to attribute inspector and set the prototype cell to 1 and then try to run your program with proper cell identifier it will work.
HTH :)
Set tableView delegate and DataSource protocol in you viewdidload method.
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.tableView registerClass: [UITableViewCell class] forCellReuseIdentifier:#"Cell"];
self.tableview.delegate = self;
self.tableview.dataSource = self;
self.contact = [[NSArray alloc] initWithArray: [NSArray arrayWithObjects:#"Joe", #"Simon", nil]];
self.contactDetails = [[NSArray alloc] initWithArray: [NSArray arrayWithObjects: #"+689171898057", #"+689173104153", nil]];
}

Sending a data model between UITableViewControllers

I know there are already lots of questions about this but none of them have helped me yet. I have two UITableViewControllers. I want to push a QuicklistViewController (using this like a quick menu to list different shows) onto a CurrentShowViewController.
I have a Show model that only contains a name property right now. I am have trouble moving the data from my selection in QuicklistViewController to the CurrentShowViewController so that I can display the currentShow information there.
I am totally stuck on how I can do this.Please help!
Here is my CurrentShowViewController:
#import "CurrentShowViewController.h"
#import "QuicklistViewController.h"
#interface CurrentShowViewController ()
#end
#implementation CurrentShowViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
self.tabBarItem.image = [UIImage imageNamed:#"tab_icon_episodes.png"];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
//self.navigationItem.rightBarButtonItem = self.editButtonItem;
// Add a UIBarButton button that will display a Quicklist Modal View
UIBarButtonItem *quicklistButton = [[UIBarButtonItem alloc] initWithTitle:#"Quicklist"
style:UIBarButtonItemStylePlain
target:self
action:#selector(quicklistButtonPressed)];
self.navigationItem.leftBarButtonItem = quicklistButton;
self.currentShow = [[Show alloc] init];
NSLog(#"Current show name is: %#", self.currentShow.name);
self.title = self.currentShow.name;
}
- (void) viewWillAppear:(BOOL)animated {
self.title = self.currentShow.name;
}
- (void) quicklistButtonPressed {
QuicklistViewController *quicklistVC = [[QuicklistViewController alloc] init];
[self.navigationController pushViewController:quicklistVC animated:YES];
}
Here is my QuicklistViewController:
#import "QuicklistViewController.h"
#import "CurrentShowViewController.h"
#interface QuicklistViewController ()
#end
#implementation QuicklistViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
self.title = #"Quicklist";
self.tabBarItem.image = [UIImage imageNamed:#"tab_icon_quicklist.png"];
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:#"Back"
style:UIBarButtonItemStylePlain
target:self
action:#selector(backButtonPressed)];
self.navigationItem.leftBarButtonItem = backButton;
// Create a temp array of Show objects filled with test data
NSMutableArray *temp= [[NSMutableArray alloc] init];
[temp addObject:[[Show alloc] initWithName:#"The Walking Dead"]];
[temp addObject:[[Show alloc] initWithName:#"How I Met Your Mother"]];
[temp addObject:[[Show alloc] initWithName:#"Grey's Anatomy"]];
[temp addObject:[[Show alloc] initWithName:#"The Mentalist"]];
[temp addObject:[[Show alloc] initWithName:#"Stargate SG1"]];
NSArray *testShows = [[NSArray alloc] initWithArray:temp];
self.shows = testShows;
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
self.currentShow = [[Show alloc] init];
}
- (void) backButtonPressed {
//Archive changes to currentShow object
[Show saveShow:self.currentShow];
[self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#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 [self.shows count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"Cell"];
}
cell.textLabel.text = [self.shows[indexPath.row] name];
return cell;
}
- (void) tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
// Change the current show to the selected show
self.currentShow = self.shows[indexPath.row];
//Archive changes to currentShow object
[Show saveShow:self.currentShow];
}
Use delegation.
CurrentShowViewController
- (void) quicklistButtonPressed
{
QuicklistViewController *quicklistVC = [[QuicklistViewController alloc] init];
quicklistVC.delegate = self;
[self.navigationController pushViewController:quicklistVC animated:YES];
}
- (void) selectedShow:(Show) show
{
// show : current show
}
QuicklistViewController
#protocol QuicklistViewControllerDelegate
- (void) selectedShow:(Show) show
#end
#property (nonatomic, weak) id delegate;
- (void) backButtonPressed
{
//Archive changes to currentShow object
[Show saveShow:self.currentShow];
[delegate selectedShow:self.currentShow];
[self.navigationController popViewControllerAnimated:YES];
}
You've mistakenly implemented didDeselectRowAtIndexPath instead of didSelectRowAtIndexPath.

to use [self presentModalViewController: animated:] and black screen

I create one program that show list of book from url in tableview (any book has many images)
I want when to click any cell to go in next page (next page is UIScroll that show images) and show images of that book
I have one problem that it is when to click any cell and when go next page show black screen instead UIScrollView include many images.
this is my code :
RecipeViewController.h
#import "RecipeViewController.h"
#interface RecipeViewController : UITableViewController<UITableViewDataSource,UITableViewDelegate>
#property (nonatomic,strong) IBOutlet UITableView *table;
#end
RecipeViewController.m
#import "RecipeViewController.h"
#import "Recipe.h"
#import "DetailViewController.h"
#implementation RecipeViewController
{
NSMutableArray *recipes;
NSInteger num;
}
#synthesize table;
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.title = #"Recipe Book";
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:#"Back" style:UIBarButtonItemStyleBordered target:nil action:nil];
[[self navigationItem] setBackBarButtonItem:backButton];
NSString *numberbook = [[NSString alloc]initWithContentsOfURL:[NSURL URLWithString:#"http://192.168.1.100/mamal/book.php?all"]];
NSInteger numbook = [numberbook integerValue];
for (int i = 1; i <= numbook; i++)
{
Recipe *si = [Recipe new];
//NSLog(#"%d,%#",i,si);
NSString *c = [[NSString alloc]initWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://192.168.1.100/mamal/book.php?info=1&b=%d",i]]];
NSData *data = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://192.168.1.100/mamal/book.php?p=1&b=%d",i]]];
si.name = [NSString stringWithString:c];
si.imageFile = data;
if(!recipes){
recipes = [NSMutableArray array];
}
[recipes addObject:si];
}
num = numbook;
// Remove table cell separator
[self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
// Assign our own backgroud for the view
self.parentViewController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"common_bg"]];
self.tableView.backgroundColor = [UIColor clearColor];
// Add padding to the top of the table view
UIEdgeInsets inset = UIEdgeInsetsMake(5, 0, 0, 0);
self.tableView.contentInset = inset;
}
#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 recipes.count;
}
- (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];
}
// Display recipe in the table cell
Recipe *recipe = [recipes objectAtIndex:indexPath.row];
UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
recipeImageView.image = [UIImage imageWithData:recipe.imageFile];
UILabel *recipeNameLabel = (UILabel *)[cell viewWithTag:101];
recipeNameLabel.text = recipe.name;
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
DetailViewController *obj = [[DetailViewController alloc]init];
int x = (indexPath.row)+1;
NSLog(#"x : %d",x);
obj.yourValue = [NSString stringWithFormat:#"%d",(indexPath.row)+1];
NSLog(#"yourValue1 : %#",obj.yourValue);
obj.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:obj animated:YES];
}
#end
DetailViewController.h
#import <UIKit/UIKit.h>
#import "Recipe.h"
#import "RecipeViewController.h"
#interface DetailViewController : UIViewController<UIScrollViewDelegate>
{
UIScrollView *scroller;
}
#property (nonatomic,strong) IBOutlet UIScrollView *scroller;
#property (nonatomic,strong) Recipe *rec;
#property (nonatomic,strong) NSString *yourValue;
#end
DetailViewController.m
#import "DetailViewController.h"
#implementation DetailViewController
#synthesize scroller,yourValue;
- (void)viewDidLoad
{
[super viewDidLoad];
int m1 = [self.yourValue integerValue];
NSLog(#"M1 : %d",m1);
NSString *bookID = [[NSString alloc]initWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://192.168.1.100/mamal/book.php?info=0&b=%d",m1]]];
NSInteger num1 = [bookID integerValue];
NSLog(#"%d",num1);
for (int i = 1; i <= num1; i++)
{
NSString *s = [NSString stringWithFormat:#"http://192.168.1.100/mamal/book.php?p=%d&b=%d",i,m1];
NSData *dat = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:s]];
NSLog(#"%#",s);
UIImageView *imagen = [[UIImageView alloc] initWithImage:[UIImage imageWithData:dat]];
imagen.frame = CGRectMake((i-1)*320, 0, 320, 460);
[scroller addSubview:imagen];
}
scroller.delegate = self;
scroller.contentSize = CGSizeMake(320*num1, 460);
scroller.pagingEnabled = YES;
}
#end
I have just solved this problem, if you are using StoryBoard you have to init the view controller this way:
UIStoryboard *storybrd = [UIStoryboard storyboardWithName:#"MainStoryboard" bundle:nil];
storybrd = [UIStoryboard storyboardWithName:#"MainStoryboard" bundle:nil];
YourViewController *newVC =[storybrd instantiateViewControllerWithIdentifier:#"YourVCId"];
You have to put your identifier in the storyboard, selecting the view you want to show and then selecting the identity inspector, there you have the option to write the id that you want.
You need to call:
[[DetailViewController alloc]initWithNibName:#"nibName" bundle:nil]; rather than just [[DetailViewController alloc]init]; as at this point, it doesn't have an Xib to inflate (unless you overrode the init method)
You not at all calling DetailViewController How it shows the image .Try this in didSelectRowAtIndexPath: may help you
DetailViewController *DVC = [[DetailViewController alloc] initWithNibName:nil bundle:nil];
[self.navigationController pushViewController:DVC animated:YES];

Resources