setEditing method causing SIGABRT - ios

I'm working form the big nerd ranch book, iphone programming. I'm working through Chapt 11 where you implement your own setEditing method:
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
[super setEditing:editing animated:animated];
if( editing) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[teams count] inSection:0];
NSArray *paths = [NSArray arrayWithObject:indexPath];
[[self tableView] insertRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationLeft];
}
else {
/*
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[teams count] inSection:0];
NSArray *paths = [NSArray arrayWithObject:indexPath];
[[self tableView] deleteRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationFade];
*/
}
}
When I run this the whole app does a Sigabort without any info other than that. The line that seems to cause the problem is this one:
[[self tableView] insertRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationLeft];
I'm not sure what I'm doing wrong. What else would be good to see?
This is the whole file:
//
// TeamsViewController.m
// TeamTrackerClient
//
// Created by Mark Steudel on 3/4/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#import "TeamsViewController.h"
#import "Team.h"
#implementation TeamsViewController
-(id) init
{
self = [super initWithStyle:UITableViewStyleGrouped];
teams = [[NSMutableArray alloc] init];
Team *team = [[Team alloc] init];
team.teamName = [NSString stringWithFormat: #"Fighting Axons"];
team.teamCode = [NSString stringWithFormat: #"FA1"];
[teams addObject:team];
Team *team2 = [[Team alloc] init];
team2.teamName = [NSString stringWithFormat: #"Pipers Peddlers"];
team2.teamCode = [NSString stringWithFormat: #"PP1"];
[teams addObject:team2];
return self;
}
- (id) initWithStyle:(UITableViewStyle)style
{
return [self init];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
}
*/
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (UIView *) headerView
{
if( headerView)
return headerView;
UIButton *editButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[editButton setTitle: #"Edit" forState: UIControlStateNormal];
float w = [[UIScreen mainScreen] bounds].size.width;
CGRect editButtonFrame = CGRectMake(8.0, 8.0, w - 16.0, 30.0);
[editButton setFrame:editButtonFrame];
[editButton addTarget:self
action:#selector(editingButtonPressed:)
forControlEvents:UIControlEventTouchUpInside];
CGRect headerViewFrame = CGRectMake(0, 0, w, 48);
headerView = [[UIView alloc] initWithFrame:headerViewFrame];
[headerView addSubview:editButton];
return headerView;
}
- (void) editingButtonPressed: (id) sender
{
if( [self isEditing] ) {
[sender setTitle:#"Edit" forState:UIControlStateNormal];
[self setEditing:NO animated:YES];
}
else {
[sender setTitle: #"Done" forState:UIControlStateNormal];
[self setEditing:YES animated:YES];
}
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
return [self headerView];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return [[self headerView] frame].size.height;
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
Team *t = [teams objectAtIndex:[sourceIndexPath row]];
[teams removeObjectAtIndex:[sourceIndexPath row]];
[teams insertObject:t atIndex:[destinationIndexPath row]];
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if( editingStyle == UITableViewCellEditingStyleDelete ) {
[teams removeObjectAtIndex:[indexPath row]];
[tableView deleteRowsAtIndexPaths: [NSArray arrayWithObject:indexPath] withRowAnimation: UITableViewRowAnimationFade];
}
}
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
[super setEditing:editing animated:animated];
if( editing) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[teams count] inSection:0];
NSArray *paths = [NSArray arrayWithObject:indexPath];
[[self tableView] insertRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationLeft];
}
else {
/*
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[teams count] inSection:0];
NSArray *paths = [NSArray arrayWithObject:indexPath];
[[self tableView] deleteRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationFade];
*/
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int numberOfRows = [teams count];
if( [self isEditing] )
numberOfRows++;
return numberOfRows;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"UITableViewCell"];
if( !cell ) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"UITableViewCell"];
}
if( [indexPath row] < [teams count] ) {
Team *t = [teams objectAtIndex:[indexPath row]];
[[cell textLabel] setText:[t teamName]];
}
else {
[[cell textLabel] setText: #"Add New Item ... "];
}
Team *t = [teams objectAtIndex:[indexPath row]];
[[cell textLabel] setText:[t teamName]];
return cell;
}
#end

[[self tableView] insertRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationLeft];
this make the table view reload data ..and check the data in its datasource methods..
i believe it is crashing on
Team *t = [teams objectAtIndex:[indexPath row]];
[[cell textLabel] setText:[t teamName]];
there might be no objects in the teams array on here for the new index paths...
check by breakpointing here..

Related

Display XIB erorr nil

I am new to Swift and I am beginning to learn XIB. I want to pressing the button appears XIB.
I using liberty ARSPopover
my error :
Warning: Attempt to present on
which is already
presenting (null)
How can I solve this problem?
My code for button :
- (IBAction)btnShoPopover:(UIBarButtonItem *)sender {
ARSPopover *popoverController = [ARSPopover new];
popoverController.sourceView = self.view;
popoverController.sourceRect = CGRectMake(370,0, 0, 0);
popoverController.contentSize = CGSizeMake(200,300);
popoverController.arrowDirection = UIPopoverArrowDirectionUp;
[self presentViewController:popoverController animated:YES completion:^{
[popoverController insertContentIntoPopover:^(ARSPopover *popover, CGSize popoverPresentedSize, CGFloat popoverArrowHeight) {
PopovViewController *poper = [[PopovViewController alloc] init];
[self presentViewController:poper animated:YES completion:nil];
}];
}];
}
I my xib don't download:
My code for xib controller:
#interface PopovViewController ()
#end
#implementation PopovViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
My controller:
#import "ResourseTableViewController.h"
#import "ProbaViewController.h"
#interface ResourseTableViewController ()
#end
#implementation ResourseTableViewController
#synthesize arrayOriginal;
#synthesize arForTable;
- (void)viewDidLoad {
[super viewDidLoad];
NSDictionary *dTmp=[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"data" ofType:#"plist"]];
self.arrayOriginal=[dTmp valueForKey:#"Objects"];
self.arForTable=[[NSMutableArray alloc] init] ;
[self.arForTable addObjectsFromArray:self.arrayOriginal];
SWRevealViewController *revealViewController = self.revealViewController;
if ( revealViewController )
{
[self.sidebarButton setTarget: self.revealViewController];
[self.sidebarButton setAction: #selector( revealToggle: )];
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.arForTable 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] ;
}
[cell setIndentationLevel:[[[self.arForTable objectAtIndex:indexPath.row] valueForKey:#"level"] intValue]];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSDictionary *d=[self.arForTable objectAtIndex:indexPath.row];
NSLog(#"Selected index data %#",d);
if([d valueForKey:#"Objects"]) {
NSArray *ar=[d valueForKey:#"Objects"];
BOOL isAlreadyInserted=NO;
for(NSDictionary *dInner in ar ){
NSInteger index=[self.arForTable indexOfObjectIdenticalTo:dInner];
isAlreadyInserted=(index>0 && index!=NSIntegerMax);
if(isAlreadyInserted) break;
}
if(isAlreadyInserted) {
[self miniMizeThisRows:ar];
} else {
NSUInteger count=indexPath.row+1;
NSMutableArray *arCells=[NSMutableArray array];
for(NSDictionary *dInner in ar ) {
[arCells addObject:[NSIndexPath indexPathForRow:count inSection:0]];
[self.arForTable insertObject:dInner atIndex:count++];
}
[tableView insertRowsAtIndexPaths:arCells withRowAnimation:UITableViewRowAnimationNone];
}
}
}
- (IBAction)btnPopover:(id)sender {
ARSPopover *popoverController = [ARSPopover new];
popoverController.sourceView = self.view;
popoverController.sourceRect = CGRectMake(370,0, 0, 0);
popoverController.contentSize = CGSizeMake(200,300);
popoverController.arrowDirection = UIPopoverArrowDirectionUp;
[self presentViewController:popoverController animated:NO completion:^{
[popoverController insertContentIntoPopover:^(ARSPopover *popover, CGSize popoverPresentedSize, CGFloat popoverArrowHeight) {
ProbaViewController *poper = [[ProbaViewController alloc] init];
CGFloat width = popoverPresentedSize.width;
CGFloat height = popoverPresentedSize.height - popoverArrowHeight;
poper.view.frame = CGRectMake(0, 0, width, height);
popover.view.layer.backgroundColor = [UIColor clearColor].CGColor;
[popover.view addSubview:poper.view];
}];
}];
}
-(void)miniMizeThisRows:(NSArray*)ar{
for(NSDictionary *dInner in ar ) {
NSUInteger indexToRemove=[self.arForTable indexOfObjectIdenticalTo:dInner];
NSArray *arInner=[dInner valueForKey:#"Objects"];
if(arInner && [arInner count]>0){
[self miniMizeThisRows:arInner];
}
if([self.arForTable indexOfObjectIdenticalTo:dInner]!=NSNotFound) {
[self.arForTable removeObjectIdenticalTo:dInner];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:
[NSIndexPath indexPathForRow:indexToRemove inSection:0]
]
withRowAnimation:UITableViewRowAnimationNone];
}
}
}
#end
Skimming the docs, it looks like the library is very versatile with respect to what's presented in the popover. Your code provides a clue that you hope to present a custom view controller within it (a PopovViewController).
EDIT Let's find out first where the problem lies. If everything else is working properly, then this code should present a green box...
[self presentViewController:popoverController animated:YES completion:^{
[popoverController insertContentIntoPopover:^(ARSPopover *popover, CGSize popoverPresentedSize, CGFloat popoverArrowHeight) {
CGFloat width = popoverPresentedSize.width;
CGFloat height = popoverPresentedSize.height - popoverArrowHeight;
UIView *test = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, height)];
test.backgroundColor = [UIColor greenColor];
[popover.view addSubview:test];
}];
}];
If that works, we can proceed to discovering why your PopovViewController's view is causing trouble. (My guess is that it's presentation is triggering some other presentation animation that conflicts with the 3rd party library.
If you get a working green view with no warnings or errors, post the code for PopovViewController's viewDidLoad, viewWillAppear, ...didAppear, ...didLayout, etc.

How to show selected checked TableViewCell in IOS(Objective c)

Hi friends I am new in IOS. I am creating a table view of state list. On button click I'm showing a TableView on popup. Code for creating state list is
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
selectedState = [NSMutableArray new];
UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screenWidth-50, screenHeight-50)];
mytableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, screenWidth-50, screenHeight-100)];
mytableview.delegate =self;
mytableview.dataSource=self;
[contentView addSubview:mytableview];
UIButton *save = [[UIButton alloc] initWithFrame:CGRectMake(0, screenHeight-100, screenWidth-50, 50)];
[save setTitle:#"SAVE" forState:UIControlStateNormal];
save.titleLabel.font = [UIFont systemFontOfSize:14];
[save setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[save addTarget:self action:#selector(saveActionForState:) forControlEvents:UIControlEventTouchUpInside];
[save setBackgroundColor:[UIColor colorWithRed:41.0/255.0 green:178.0/255.0 blue:165.0/255.0 alpha:1.0]];
[contentView addSubview:save];
[[KGModal sharedInstance] showWithContentView:contentView andAnimated:YES];
For table creation code is
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [stateList count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CRTableViewCellIdentifier = #"cellIdentifier";
if(selectStateButton ==1){
CRTableViewCell *cell = (CRTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CRTableViewCellIdentifier];
if (cell == nil) {
cell = [[CRTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CRTableViewCellIdentifier];
}
NSString *text = [stateList objectAtIndex:[indexPath row]];
cell.textLabel.font = [UIFont systemFontOfSize:12.0];
cell.isSelected = [selectedState containsObject:text] ? YES : NO;
cell.textLabel.text = text;
return cell;
}
}
On selection of table cell checked the cell of IOS.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(selectStateButton ==1){
//[selectedStatesForSelect2 removeAllObjects];
NSString *text = [stateList objectAtIndex:[indexPath row]];
NSInteger indexings = [indexPath row]+1;
if ([selectedState containsObject:text]){
[selectedState removeObject:text];
[selectedStatesId removeObject:[NSString stringWithFormat:#"%ld", (long)indexings]];
}else{
//NSLog(#"count%lu indexing %#",(unsigned long)[selectedState count],selectedStatesId);
[selectedState addObject:text];
[selectedStatesId addObject:[NSString stringWithFormat:#"%ld", (long)indexings]];
[selectedStatesForSelect2 addObject:[NSString stringWithFormat:#"%ld", (long)indexings]];
NSLog(#"select%#count%lu",selectedStatesForSelect2,(unsigned long)[selectedState count]);
if([selectedState count] > 3){
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Hold On..." message:#"You can't select more than three states." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
[selectedState removeObject:text];
[selectedStatesId removeObject:[NSString stringWithFormat:#"%ld", (long)indexings]];
}
}
}
That seen like this. When user select first time it works very good. But after closing the table view, when user again open the state list I want to show the previous selected item. Thats not working properly. I'm using a library for check "CRMultiRowSelector".Please help me.
I will give what you ask.I tried many times this.It works perfectly
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
#property (strong, nonatomic) IBOutlet UITableView *tableViewCheckMarkPreviousSelectionUpdate;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
{
NSMutableArray *arrProductSelection,*arrProductSelectDeSelectCheckMark;
NSArray *arrayFetchFromDefaults;
}
#end
#implementation ViewController
#synthesize tableViewCheckMarkPreviousSelectionUpdate;
- (void)viewDidLoad
{
[super viewDidLoad];
arrProductSelection = [[NSMutableArray alloc]initWithObjects:#"iPhone",#"iPad",#"iPod",#"iTV",#"iWatch",#"iMac",nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)viewWillAppear:(BOOL)animated
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
arrayFetchFromDefaults = [userDefaults objectForKey:#"selectedcheckmark"];
arrProductSelectDeSelectCheckMark = [[NSMutableArray alloc]initWithArray:arrayFetchFromDefaults];
if(arrProductSelectDeSelectCheckMark.count == 0)
{
arrProductSelectDeSelectCheckMark = [[NSMutableArray alloc]init];
for(int j=0;j<[arrProductSelection count];j++)
{
[arrProductSelectDeSelectCheckMark addObject:#"deselected"];
}
}
[tableViewCheckMarkPreviousSelectionUpdate reloadData];
}
#pragma mark - UITableViewDataSource Methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arrProductSelection.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *strCell = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strCell];
if(cell==nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strCell];
}
if([[arrProductSelectDeSelectCheckMark objectAtIndex:indexPath.row] isEqualToString:#"deselected"])
cell.accessoryType = UITableViewCellAccessoryNone;
else
cell.accessoryType = UITableViewCellAccessoryCheckmark;
cell.textLabel.text = [arrProductSelection objectAtIndex:indexPath.row];
return cell;
}
#pragma mark - UITableViewDelegate Methods
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
#try
{
CGPoint touchPoint = [cell convertPoint:CGPointZero toView:tableViewCheckMarkSelectionUpdate];
NSIndexPath *indexPath = [tableViewCheckMarkSelectionUpdate indexPathForRowAtPoint:touchPoint];
NSLog(#"%#",arrProductSelectDeSelectCheckMark);
if([arrProductSelectDeSelectCheckMark count]==0)
{
for(int i=0; i<[arrProductSelection count]; i++)
{
[arrProductSelectDeSelectCheckMark addObject:#"deselected"];
}
}
if([[arrProductSelectDeSelectCheckMark objectAtIndex:indexPath.row] isEqualToString:#"deselected"])
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[arrProductSelectDeSelectCheckMark replaceObjectAtIndex:indexPath.row withObject:#"selected"];
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
[arrProductSelectDeSelectCheckMark replaceObjectAtIndex:indexPath.row withObject:#"deselected"];
}
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:arrProductSelectDeSelectCheckMark forKey:#"selectedcheckmark"];
[defaults synchronize];
}
#catch (NSException *exception) {
NSLog(#"The exception is-%#",exception);
}
}
#end
You have to save indexPaths and while creating the cell you have to again reassign state of cell. If it is selected or not.
In
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{}
in this method keep selected indexPaths and check for same indexPaths in cellPathForRowIndexPath, if there there show as checked otherwise unchecked.

UITableViewCell delete does not use proper UITableViewRowAnimation

When a row is deleted it always slides to left no matter what animation value I pass. I would like it to slide up similar to many of the stock apps.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
self.tableData = [][[self.tableData mutableCopy] removeObjectAtIndex:indexPath.row] copy];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];
}
}
Here is the full tableview controller code, it is has a lot in it. That is the reason I didn't post it at first.
#interface FMListViewController ()
#property (strong) NSArray *currentLocations;
#property (assign) BOOL isEditing;
#end
#implementation FMListViewController
- (void)viewDidLoad {
[super viewDidLoad];
UISegmentedControl *viewType = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:#"List", #"Map", nil]];
CGRect viewTypeRect = viewType.frame;
viewTypeRect.size.width = 150.0f;
viewType.frame = viewTypeRect;
viewType.selectedSegmentIndex = 0;
[viewType addTarget:self action:#selector(viewTypeChange:) forControlEvents:UIControlEventValueChanged];
self.navigationItem.titleView = viewType;
self.currentLocations = [[FMLocations sharedManager] allLocations];
//watch for weather updates
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(weatherUpdated) name:#"weatherUpdated" object:nil];
//watch for changes to saved locations
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(locationsUpdated) name:#"locationsUpdated" object:nil];
self.isEditing = NO;
}
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
// this UIViewController is about to re-appear, make sure we remove the current selection in our table view when swiping back occurs
NSIndexPath *tableSelection = [self.tableView indexPathForSelectedRow];
[self.tableView deselectRowAtIndexPath:tableSelection animated:NO];
[self.navigationController setToolbarHidden:YES animated:NO];
}
- (void)viewTypeChange:(UISegmentedControl *)segControl{
NSLog(#"change to map");
[(FMNavController *)[self navigationController] changeViewType];
segControl.selectedSegmentIndex = 0;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)weatherUpdated{
[self.tableView reloadData];
[self.refreshControl endRefreshing];
}
- (void)locationsUpdated{
if(self.isEditing){
self.currentLocations = [[FMLocations sharedManager] savedLocations];
}else{
self.currentLocations = [[FMLocations sharedManager] allLocations];
}
[self.tableView reloadData];
}
#pragma mark - Table Editing Stuff
- (IBAction)toggleEditing:(id)sender{
if(self.isEditing){
self.isEditing = NO;
self.currentLocations = [[FMLocations sharedManager] allLocations];
[self.tableView reloadData];
UIBarButtonItem *newRightItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:#selector(toggleEditing:)];
self.navigationItem.rightBarButtonItem = newRightItem;
[self.tableView setEditing:NO animated:YES];
}else{
self.isEditing = YES;
self.currentLocations = [[FMLocations sharedManager] savedLocations];
[self.tableView reloadData];
UIBarButtonItem *newRightItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(toggleEditing:)];
self.navigationItem.rightBarButtonItem = newRightItem;
[self.tableView setEditing:YES animated:YES];
}
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.row == 0 && [[FMLocations sharedManager] currentLocation] && !self.isEditing){
return NO;
}
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
//add code here for when you hit delete
NSMutableArray *newLocations;
int arrayOffset = 0;
if([[FMLocations sharedManager] currentLocation] && !self.isEditing){
arrayOffset = -1;
}
newLocations = [[[FMLocations sharedManager] savedLocations] mutableCopy];
int itemToRemove = (int)indexPath.row + arrayOffset;
if(itemToRemove < 0 || itemToRemove > [newLocations count]){
NSLog(#"invalid item to remove");
}else{
[newLocations removeObjectAtIndex:itemToRemove];
[[FMLocations sharedManager] saveSavedLocations:[newLocations copy]];
if(self.isEditing){
self.currentLocations = [[FMLocations sharedManager] savedLocations];
}else{
self.currentLocations = [[FMLocations sharedManager] allLocations];
}
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];
}
}
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.row == 0 && [[FMLocations sharedManager] currentLocation] && !self.isEditing){
return NO;
}
return YES;
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{
NSMutableArray *editableLocations = [[[FMLocations sharedManager] savedLocations] mutableCopy];
if(editableLocations && [editableLocations count] > sourceIndexPath.row && [editableLocations count] > destinationIndexPath.row){
NSInteger fromIndex = sourceIndexPath.row;
NSInteger toIndex = destinationIndexPath.row;
id object = [editableLocations objectAtIndex:fromIndex];
[editableLocations removeObjectAtIndex:fromIndex];
[editableLocations insertObject:object atIndex:toIndex];
[[FMLocations sharedManager] saveSavedLocations:[editableLocations copy]];
}
}
#pragma mark - Refresh control action
- (IBAction)doRefreshTable:(id)sender{
[[ForecastManager sharedManager] updateForecasts];
}
#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.currentLocations count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//NSLog(#"getting cell");
FMTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"FMLocationCell" forIndexPath:indexPath];
NSDictionary *theLocation = [self.currentLocations objectAtIndex:indexPath.row];
// Configure the cell...
cell.locationLabel.text = [[theLocation objectForKey:#"name"] uppercaseString];
WeatherObject *locationWeather = [[ForecastManager sharedManager] weatherObjectForLocation:[[theLocation objectForKey:#"id"] intValue]];
[cell setCurrentTemp:locationWeather.currentTemp];
[cell configureForecastViews:locationWeather.forecastObjects];
[cell.weatherPreviewContainer setNeedsDisplay];
return cell;
}
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
if([segue.identifier isEqualToString:#"showLocation"]){
FMDetailViewController *detailController = [segue destinationViewController];
NSDictionary *theLocation = [self.currentLocations objectAtIndex:self.tableView.indexPathForSelectedRow.row];
detailController.navigationItem.title = [theLocation objectForKey:#"name"];
detailController.detailLocation = theLocation;
}
}
You can try below solutions:
1) Replace your line with the below one
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationTop];
2) Change the code with the below one:
[self.tableView beginUpdates];
[self.tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationTop];
[self.tableView endUpdates];
Hope this helps!
please try with that
don't delete cell directly first make its cellheight to zero using. NSIndexPath *deleteIndexPath;
wirte below code before delete
[tbl beginUpdates];
deleteIndexPath = indexPath;
[tbl reloadRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
[tbl endUpdates];
and in set hight method use
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{ if (indexPath == deleteIndexPath) {
return 0;
}
return 50;
}

how to push tableview to UIView dynamically in iOS?

i am displaying list content in table view now i want when i click
one menu of list that menu content display in UIView on next screen
. how to push UITableView to UIView dynamically in iOS.
#import "SmsCategoryTitleTableViewController.h"
#import "CategoryMainWindowViewController.h"
#import "AppDelegate.h"
#import "FMDatabase.h"
#import "FMResultSet.h"
#import "SmsTitle.h"
#import "SMSCategory.h"
#import"smsDisplayViewController.h"
#interface SmsCategoryTitleTableViewController ()
#end
#implementation SmsCategoryTitleTableViewController
#synthesize theSearchBar,Id;
#synthesize theTableView;
#synthesize array;
#synthesize disableViewOverlay;
#synthesize Arrayobject;
- (void)viewDidLoad
{
[super viewDidLoad];
[self SearchBarCode];
[self GetTableData];
[self.tableView reloadData];
filteredContentList = [[NSMutableArray alloc] init];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:#selector(dismissKeyboard)];
[self.view addGestureRecognizer:tap];
// [self performSelector:#selector(push:) withObject:nil afterDelay:0.2f];
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
}
return self;
}
-(void)GetTableData
{
array = [[NSMutableArray alloc] init];
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentDir = [docPaths objectAtIndex:0];
self.databasePath = [documentDir stringByAppendingPathComponent:#"SMS.sqlite"];
FMDatabase *database = [FMDatabase databaseWithPath:self.databasePath];
[database setLogsErrors:TRUE];
[database open];
NSString *anQuery = [[NSString alloc]initWithFormat:#"SELECT * FROM SMSnJokes
where CategoryId=%#",self.Id];
FMResultSet *results = [database executeQuery:anQuery];
while([results next])
{
SmsTitle *title=[[SmsTitle alloc]init];
title.Id = [results stringForColumn:#"Id"];
title.CategoryId = [results stringForColumn:#"CategoryId"];
title.Title = [results stringForColumn:#"Title"];
[array addObject:title];
// NSLog(#"SMS LIST %#",title.Title);
}
[database close];
}
-(void)SearchBarCode
{
self.disableViewOverlay = [[UIView
alloc]initWithFrame:CGRectMake(0.0f,44.0f,320.0f,0)];
self.disableViewOverlay.backgroundColor=[UIColor lightGrayColor];
self.disableViewOverlay.alpha = 0;
theSearchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 5, 374.0f, 50)];
theSearchBar.delegate =self;
[self.tableView addSubview:theSearchBar];
self.navigationItem.title=#"SMS LIST";
[[self tableView] setTableHeaderView:theSearchBar];
}
- (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.
if (isSearching)
{
return [filteredContentList count];
}
else
{
return [array count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath
{
static NSString *CellIdentifier=#"Cell";
UITableViewCell *cell=[tableView
dequeueReusableCellWithIdentifier:CellIdentifier ];
if(!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] ;
}
if (isSearching)
{
cell.textLabel.text = [filteredContentList objectAtIndex:indexPath.row];
}
else
{
SmsTitle *title = [array objectAtIndex:indexPath.row];
[cell.textLabel setText:[NSString stringWithFormat:#"%# ",[title
valueForKey:#"Title"]]];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (void)searchTableList
{
NSString *searchString =theSearchBar.text;
filteredContentList = [[NSMutableArray alloc]init];
[filteredContentList removeAllObjects];
for (SmsTitle *title in array)
{
NSString *tempStr = title.Title;
NSComparisonResult result = [tempStr compare:searchString options:
(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0,
[searchString length])];
if (result == NSOrderedSame)
{
[filteredContentList addObject:title.Title];
}
}
}
#pragma mark - Search Implementation
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self.theSearchBar resignFirstResponder];
}
- (void) dismissKeyboard
{
[self.theSearchBar becomeFirstResponder];
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
isSearching = YES;
[theSearchBar setShowsCancelButton:YES animated:YES];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
NSLog(#"Text change - %d",isSearching);
//Remove all objects first.
[filteredContentList removeAllObjects];
if([searchText length] != 0) {
isSearching = YES;
[self searchTableList];
}
else {
isSearching = NO;
}
[self.tableView reloadData];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
theSearchBar.text=nil;
[theSearchBar setShowsCancelButton:NO animated:YES];
[theSearchBar resignFirstResponder];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[theSearchBar setShowsCancelButton: YES animated: YES];
[self searchTableList];
[searchBar resignFirstResponder];
}
- (void)searchBar:(UISearchBar *)searchBar activate:(BOOL) active
{
self.theTableView.allowsSelection = !active;
self.theTableView.scrollEnabled = !active;
if (!active)
{
[disableViewOverlay removeFromSuperview];
[searchBar resignFirstResponder];
}
else
{
self.disableViewOverlay.alpha = 0;
[self.view addSubview:self.disableViewOverlay];
[UIView beginAnimations:#"FadeIn" context:nil];
[UIView setAnimationDuration:0.5];
self.disableViewOverlay.alpha = 0.6;
[UIView commitAnimations];
NSIndexPath *selected = [self.theTableView indexPathForSelectedRow];
if (selected)
{
[self.theTableView deselectRowAtIndexPath:selected
animated:NO];
}
}
[searchBar setShowsCancelButton:active animated:YES];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
[self.theSearchBar resignFirstResponder];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
textField.returnKeyType=UIReturnKeyDefault ;
return[textField resignFirstResponder];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath
*)indexPath
{
smsDisplayViewController *viewController1 = [[smsDisplayViewController alloc]
init];
[self.navigationController pushViewController:viewController1 animated:YES];
}
Ok got your point. I think you want to pass data of selected cell to
next UIViewController. Assume, you want to pass cell title label and
you have an array of objects. In yoursmsDisplayViewController.h
#import <UIKit/UIKit.h>
#interface smsDisplayViewController : UIViewController
#property (strong, nonatomic) NSString *cellName;
Now in your SmsCategoryTitleTableViewController.m you have
NSMutableArray *nameList;
Then in your table view delegate method
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
smsDisplayViewController *viewController1 = [self.storyboard instantiateViewControllerWithIdentifier:#"LoginIdentifier"];
viewController1.cellName=[nameList objectAtIndex:indexPath.row];
[self.navigationController pushViewController:viewController1 animated:YES];
}
UPDATE This is the code you posted first in your question.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
smsDisplayViewController *viewController1 = [[smsDisplayViewController
alloc] initWithNibName:#"viewController1" bundle:nil];
[self.navigationController pushViewController:viewController1 animated:YES];
}
Now the wrong thing you are doing here
isinitWithNibName:#"viewController1". If you are not using any nib
file then your code should be
smsDisplayViewController *viewController1 = [[smsDisplayViewController alloc] init];
[self.navigationController pushViewController:viewController1 animated:YES];
You can use Accessory Buttons in UITableView or learn more about segues.
You have to use prepareForSegue: to pass data to another ViewController.
You can learn it from Here which teaches you how to transfer data between ViewControllers while using Segue.

Getting to show images in tableview's cells on the next view controller

DETAILVIEW
here's the detailview code showing the erroneous sections.howing the details of different sections of cars,such as suv,sedan,hatchback.this code show different cars of types of suvs,sedans,hatchbacks in forms of a
- (void)viewDidLoad
{
Hatchback = [[NSMutableArray alloc]initWithObjects:#"Hyundai i10",#"Hyundai i20",#"Maruti Suzuki Swift",#"Maruti Suzuki wagonR",#"Honda brio",#"Ford figo", nil];
SUV = [[NSMutableArray alloc]initWithObjects:#"Tata safari storme",#"Mahindra scorpio",#"Mahindra xuv 500",#"Renault duster", nil];
Sedan = [[NSMutableArray alloc]initWithObjects:#"Honda city",#"Maruti Suzuki dzire",#"Hyundai verna",#"Skoda octavia",#"Honda civic",#"Honda amaze",#" Ford fiesta", nil];
HatchbackImg = [[NSMutableArray alloc]initWithObjects:#"i10.jpg",#"i20.jpg",#"Swift.jpeg",#"wagonR.jpg",#"brio.jpg",#"figo.jpg",#"indica.jpg",#"beat.jpg",nil];
SUVImg = [[NSMutableArray alloc]initWithObjects:#"safari.jpg",#"scorpio.jpg",#"xuv.jpg",#"duster.jpg", nil];
SedanImg = [[NSMutableArray alloc]initWithObjects:#"city.jpg",#"dzire.jpg",#"verna.jpg",#"octavia.jpg",#"civic.jpg",#"amaze.jpg",#"fiesta.jpg", nil];
[super viewDidLoad];
self.tableView.backgroundColor = [UIColor brownColor];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#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
{
#warning Incomplete method implementation.
// Return the number of rows in the section.
//return 0;
if (Carint ==0) {
return [Hatchback count];
} else if (Carint ==1) {
return [SUV count];
} else if (Carint ==2) {
return [Sedan count];
}
[self.tableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyCell"];
- (UIImage *)imageForRow:(NSUInteger)row
{
if (Carint == 0) {
return [UIImage imageNamed:[HatchbackImg objectAtIndex:indexPath.row]];
} else if (Carint == 1) {
return [UIImage imageNamed:[SUVImg objectAtIndex:indexPath.row]];
} else if (Carint == 2) {
return [UIImage imageNamed:[SedanImg objectAtIndex:indexPath.row]];
}
return nil;
}
- (NSString *)titleForRow:(NSUInteger)row
{
if (Carint == 0) {
return [Hatchback objectAtIndex:indexPath.row];
} else if (Carint == 1) {
return [SUV objectAtIndex:indexPath.row];
} else if (Carint == 2) {
return [Sedan objectAtIndex:indexPath.row];
}
return nil;
}
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"MyCell"];
cell.textLabel.text = [self titleForRow:indexPath.row];
cell.imageView.image = [self imageForRow:indexPath.row];
if (Carint == 0) {
cell.imageView.image=[UIImage imageNamed:[HatchbackImg objectAtIndex:indexPath.row]];
cell.textLabel.text =[Hatchback objectAtIndex:indexPath.row];
UIImageView *imageView = [[UIImageView alloc]init];
[cell.contentView addSubview:imageView];
} else if (Carint == 1) {
cell.imageView.image=[UIImage imageNamed:[SUVImg objectAtIndex:indexPath.row]];
cell.textLabel.text = [SUV objectAtIndex:indexPath.row];
UIImageView *imageView = [[UIImageView alloc]init];
[cell.contentView addSubview:imageView];
} else if (Carint == 2) {
cell.imageView.image=[UIImage imageNamed:[SedanImg objectAtIndex:indexPath.row]];
cell.textLabel.text = [Sedan objectAtIndex:indexPath.row];
UIImageView *imageView = [[UIImageView alloc]init];
[cell.contentView addSubview:imageView];
}
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
}
// Configure the cell...
return cell;
}
-(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"cellBg1.png"]];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (Carint == 0)
{
NSString *imageName = [HatchbackImg objectAtIndex:indexPath.row];
//[UIImageView setImage:[SedanImg objectAtIndex:indexPath.row]];
// [UIImageView setImage:[SedanImg objectAtIndex:indexPath.row]];
}
else if (Carint ==1)
{
NSString *imageName = [SUVImg objectAtIndex:indexPath.row];
}
else if (Carint ==2)
{
NSString *imageName = [SedanImg objectAtIndex:indexPath.row];
}
NSString *carName = [self titleForRow:indexPath.row];
UIImage *carImage = [self imageForRow:indexPath.row];
// Navigation logic may go here. Create and push another view controller.
carSelectViewController *carDetailViewController = [[carSelectViewController alloc] initWithNibName:#"carSelectViewController" bundle:nil];
carDetailViewController.carName = carName;
carDetailViewController.carImage = carImage;
[self.navigationController pushViewController:carDetailViewController animated:YES];
}
#end
You should not be storing data in the cells of a table. The cells of a table are there to display information.
First, you seem to be using an iVar Carint to display different sets of cars. First, all variables should have lowercase first letters. Second, this is a bad idea.
By doing this you are strongly coupling the table to the data it is displaying. I'll ignore this for now though.
Second, you should also be using a custom UITableViewCell subclass to create UIImageViews etc... but I'll ignore this too.
Third, you should create a Class called Car. Then give the class Car two properties, name and image and actually you could give it type too but again I'll ignore this.
NOTE just because I am ignoring them doesn't mean you should too. Think of these first three as hints of what to work on next.
Fourth, create a function that will return the image for the row. Like this...
- (UIImage *)imageForRow:(NSUInteger)row
{
if (Carint == 0) {
return [UIImage imageNamed:[HatchbackImg objectAtIndex:indexPath.row]];
} else if (Carint == 1) {
return [UIImage imageNamed:[SUVImg objectAtIndex:indexPath.row]];
} else if (Carint == 2) {
return [UIImage imageNamed:[SedanImg objectAtIndex:indexPath.row]];
}
return nil;
}
and the title. Like this...
- (NSString *)titleForRow:(NSUInteger)row
{
if (Carint == 0) {
return [Hatchback objectAtIndex:indexPath.row];
} else if (Carint == 1) {
return [SUV objectAtIndex:indexPath.row];
} else if (Carint == 2) {
return [Sedan objectAtIndex:indexPath.row];
}
return nil;
}
This means that you can change your current methods like so...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"MyCell"];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
}
cell.textLabel.text = [self titleForRow:indexPath.row];
cell.imageView.image = [self.imageForRow:indexPath.row];
return cell;
}
and...
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *carName = [self titleForRow:indexPath.row];
UIImage *carImage = [self imageForRow:indexPath.row];
// Navigation logic may go here. Create and push another view controller.
// OMG! Fix the naming conventions. Class names should start with uppercase letters.
carSelectViewController *carDetailViewController = [[carSelectViewController alloc] initWithNibName:#"carSelectViewController" bundle:nil];
// These won't work until you do the next bit.
carDetailViewController.carName = carName;
carDetailViewController.carImage = carImage;
// Pass the selected object to the new view controller.
[self.navigationController pushViewController: carDetailViewController animated:YES];
}
Next, add properties to the "detail view controller" like this...
#interface carSelectViewController : UIViewController
#property NSString *carName;
#property UIImage *carImage;
#end
These are then being set by the previous view controller.
Finally, use the values of these properties to display the data.
- (void)viewDidLoad
{
self.title = self.carName;
imageView.image = self.carImage;
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
For more information about doing this and especially working on those first three points you can see here...
http://www.raywenderlich.com
**CARDETAILVIEWCONTROLLER**
- (void)viewDidLoad
{
[self showData];
[super viewDidLoad];
self.tableView.backgroundColor = [UIColor brownColor];
}
-(void) showData
{
Hatchback = [[NSMutableArray alloc]init];
SUV = [[NSMutableArray alloc]init];
Sedan = [[NSMutableArray alloc]init];
//Hatchback
[Hatchback addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Hyundai i10",#"name",#"i10.jpg",#"image",nil]];
[Hatchback addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Hyundai i20",#"name",#"i20.jpg",#"image",nil]];
[Hatchback addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Maruti Suzuki Swift",#"name",#"Swift.jpeg",#"image",nil]];
[Hatchback addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Maruti Suzuki wagonR",#"name",#"wagonR.jpg",#"image",nil]];
[Hatchback addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Honda Brio",#"name",#"brio.jpg",#"image",nil]];
[Hatchback addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Ford figo",#"name",#"figo.jpg",#"image",nil]];
//SUV
[SUV addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Tata safari storme",#"name",#"safari.jpg",#"image",nil]];
[SUV addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Mahindra scorpio",#"name",#"scorpio.jpg",#"image",nil]];
[SUV addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Mahindra xuv 500",#"name",#"xuv.jpg",#"image",nil]];
[SUV addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Renault duster",#"name",#"duster.jpg",#"image",nil]];
//Sedan
[Sedan addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Honda city",#"name",#"city.jpg",#"image",nil]];
[Sedan addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"MarutiSuzuki dzire",#"name",#"dzire.jpg",#"image",nil]];
[Sedan addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Hyundai verna",#"name",#"verna.jpg",#"image",nil]];
[Sedan addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Skoda octavia",#"name",#"octavia.jpg",#"image",nil]];
[Sedan addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Honda civic",#"name",#"civic.jpg",#"image",nil]];
[Sedan addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Honda amaze",#"name",#"amaze.jpg",#"image",nil]];
[Sedan addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Ford fiesta",#"name",#"fiesta.jpg",#"image",nil]];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#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
{
#warning Incomplete method implementation.
if (Carint ==0) {
return [Hatchback count];
}
if (Carint ==1) {
return [SUV count];
}
if (Carint ==2) {
return [Sedan count];
}
[self.tableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"MyCell"];
if (Carint == 0)
{
cell.imageView.image=[UIImage imageNamed:[HatchbackImg objectAtIndex:indexPath.row]];
cell.textLabel.text =[[Hatchback objectAtIndex:indexPath.row]objectForKey:#"name"];
}
if (Carint == 1)
{
cell.imageView.image=[UIImage imageNamed:[SUVImg objectAtIndex:indexPath.row]];
cell.textLabel.text = [[SUV objectAtIndex:indexPath.row] objectForKey:#"name"];
}
if (Carint == 2)
{
cell.imageView.image=[UIImage imageNamed:[SedanImg objectAtIndex:indexPath.row]];
cell.textLabel.text = [[Sedan objectAtIndex:indexPath.row ]objectForKey:#"name"];
}
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
}
return cell;
}
-(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"cellBg1.png"]];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
carSelectViewController *car = [[carSelectViewController alloc]initWithNibName:#"carSelectViewController" bundle:nil];
if (Carint == 0)
{
car.carImageString = [[NSString alloc]initWithString:[[Hatchback objectAtIndex:indexPath.row]objectForKey:#"image"]];
car.carLabelString = [[NSString alloc]initWithString:[[Hatchback objectAtIndex:indexPath.row]objectForKey:#"image"]];
car.title = [[Hatchback objectAtIndex:indexPath.row]objectForKey:#"name" ];
}
else if (Carint ==1)
{
car.carImageString = [[NSString alloc]initWithString:[[SUV objectAtIndex:indexPath.row]objectForKey:#"image"]];
car.carLabelString = [[NSString alloc]initWithString:[[SUV objectAtIndex:indexPath.row]objectForKey:#"image"]];
car.title = [[SUV objectAtIndex:indexPath.row]objectForKey:#"name" ];
}
else if (Carint ==2)
{
car.carImageString = [[NSString alloc]initWithString:[[Sedan objectAtIndex:indexPath.row]objectForKey:#"image"]];
car.carLabelString = [[NSString alloc]initWithString:[[Sedan objectAtIndex:indexPath.row]objectForKey:#"image"]];
car.title = [[Sedan objectAtIndex:indexPath.row]objectForKey:#"name" ];
}
[self.navigationController pushViewController:car animated:YES];
}
#end
**CARSELECTVIEWCONTROLLER
#synthesize carImageString,carLabelString;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
NSString *localImgName;
- (void)viewDidLoad
{
carImage.image = [UIImage imageNamed:carImageString];
carLabel.text = carLabelString;
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)btnBook:(id)sender {
carBookViewController *Book = [[carBookViewController alloc]initWithNibName:#"carBookViewController" bundle:nil];
[self.navigationController pushViewController: Book animated:YES];
}
#end
I have tried the method of using nsdictionaries for key pair values of images & text together to make the code simpler(i guess).it goes well with the requirement of the app as well to show text & images together on the next view.
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NextViewController *viewcontroller=[NextViewController alloc]init];
viewcontroller.image=[tableView cellForRowAtIndexPath:indexPath].imageView.image;
}
Then either push or present this view Controller to show.
viewcontroller.image is cusotm property in ur next class
then on viewdidload method
set the imageView's image property to self.image

Resources