Select UITableView's row when clicking on UISwitch - iphone

I have a UITableView with UISwitchs on them.
When the switch is toggled I want to run a function. The function just logs If the switch is on or off and the row that the switch has been changed on. The problem that im having is that when I click on the switch it does not log the correct row unless I have clicked on that row before clicking the switch.
I guess my problem is that clicking the switch does not select the row. How can I make it so that it either selects the row or can I add the ID to the switch?
So switch ID "1" is "ON".
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"POICell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
//set the cell text to the catName
cell.textLabel.text = [self.catNames objectAtIndex:[indexPath row]];
//add switch
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UISwitch *switchView = [[UISwitch alloc] initWithFrame:CGRectZero];
cell.accessoryView = switchView;
[switchView setOn:YES animated:NO];
[switchView addTarget:self action:#selector(switchChanged: ) forControlEvents:UIControlEventValueChanged];
// Configure the cell...
return cell;
}
- (void) switchChanged:(id)sender {
NSString *StrCatID =[[NSString alloc]init];
StrCatID = [self.catIDs objectAtIndex:[self.inputTableView indexPathForSelectedRow].row];
UISwitch* switchControl = sender;
NSLog( #"The switch for item %# is %#",StrCatID, switchControl.on ? #"ON" : #"OFF" );
}

To find the cell that holds the switch
UISwitch *switchInCell = (UISwitch *)sender;
UITableViewCell * cell = (UITableViewCell*) swithInCell.superview;
To find the indexpath of that cell
NSIndexPath * indexpath = [myTableView indexPathForCell:cell]
In your case
- (void) switchChanged:(id)sender {
UISwitch *switchInCell = (UISwitch *)sender;
UITableViewCell * cell = (UITableViewCell*) swithInCell.superview;
NSIndexPath * indexpath = [myTableView indexPathForCell:cell]
NSString *strCatID =[[NSString alloc]init];
strCatID = [self.catIDs objectAtIndex:indexpath];
NSLog( #"The switch for item %# is %#",StrCatID, switchInCell.on ? #"ON" : #"OFF" );
}

You should set the IndexPath.row as a Tag to each Switch in cellForRowAtIndexPath Method
switchView.tag= indexPath.row;
And when switch value change .you'll get the Row number
- (void) switchChanged:(UISwitch *)sender {
int rowIndex =[sender tag];
//rowIndex you may use it further as you wanted.
}

You can retrieve the NSIndexPath for the UISwitch that was changed in the tableview. This is the same idea for any control as already answered in this post : Detecting which UIButton was pressed in a UITableView
- (void) switchChanged:(id)sender
{
CGPoint switchPositionPoint = [sender convertPoint:CGPointZero toView:[self tableView]];
NSIndexPath *indexPath = [[self tableView] indexPathForRowAtPoint:switchPositionPoint];
}
This will work for iOS7, previously I used [sender superview] but that now returns a UITableViewCellContentView inside of a UITableViewCellScrollView.

I had to do double mySwitch.superview.superview to get the proper cell.
Here's an example
- (void)switchToggle:(UISwitch *)mySwitch
{
UITableViewCell *cell = (UITableViewCell *)mySwitch.superview.superview;
NSIndexPath *indexpath = [self.tableView indexPathForCell:cell];
NSLog(#"toggle section %d rowID %d", indexpath.section, indexpath.row);
}

I think the problem is that you use dequeueReusableCellWithIdentifier, and all of your cell has the same id.

A better way to do this is determine which cell the sender is in.
- (UITableViewCell *)findCellForView:(UIView *)view
{
for (; view != nil; view = view.superview)
if ([view isKindOfClass:[UITableViewCell class]])
return view;
return nil;
}
Once you have this method. then it's a matter of replacing [self.inputTableView indexPathForSelectedRow] with
UITableViewCell *cell = [self findCellForView:sender];
NSIndexPath *indexPath = [self.inputTableView indexPathForCell:cell];

#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
#property (retain, nonatomic) IBOutlet UITableView *tableview;
#end
#interface ViewController ()
{
NSMutableArray *arr;
UITableViewCell* aCell;
UISwitch *myswitch;
}
#import "ViewController.h"
#interface ViewController ()
{
NSMutableArray *arr;
UITableViewCell* aCell;
UISwitch *myswitch;
}
#end
#implementation ViewController
#synthesize tableview;
- (void)viewDidLoad
{
[super viewDidLoad];
arr = [[NSMutableArray alloc]initWithObjects:#"1",#"2",#"3",#"4",#"5", nil];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
return [arr count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
aCell = [tableview dequeueReusableCellWithIdentifier:#"SwitchCell"];
if( aCell == nil )
{
aCell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"SwitchCell"];
aCell.textLabel.text = [arr objectAtIndex:indexPath.row];
myswitch = [[UISwitch alloc]initWithFrame:CGRectZero];
aCell.accessoryView = myswitch;
[myswitch setOn:YES animated:YES];
}
switch (indexPath.row)
{
case 0:
{
[myswitch addTarget:self action:#selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
}
break;
case 1:
{
[myswitch addTarget:self action:#selector(switchChanged1:) forControlEvents:UIControlEventValueChanged];
}
break;
}
return aCell;
}
- (void) switchChanged:(id)sender {
UISwitch *aswitch = sender;
if (aswitch.on==YES) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"hello" message:#"okfine" delegate:self cancelButtonTitle:#"done" otherButtonTitles:nil, nil];
[alert show];
}
else
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"no1" message:#"notfine" delegate:self cancelButtonTitle:#"Returnback" otherButtonTitles:nil, nil];
[alert show];
}
}
- (void) switchChanged1:(id)sender {
UISwitch *aswitch1 = sender;
if (aswitch1.on==YES) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"second" message:#"okfine" delegate:self cancelButtonTitle:#"done" otherButtonTitles:nil, nil];
[alert show];
}
else
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"no2" message:#"notfine" delegate:self cancelButtonTitle:#"Returnback" otherButtonTitles:nil, nil];
[alert show];
}
}
- (void)dealloc {
[tableview release];
[super dealloc];
}
#end

Related

How to grayout all tableview cells except selected one

I have a table view with custom cells ,there are uibuttons on custom cell ,if i select button except that cell remaining all cells should be grayouted or disabled is it possible.
// code in tableview class
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
NSLog(#"No OF rows:%d",[contents count]);
return [contents count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
static NSString *cellIdentifier = #"cell";
// Try to retrieve from the table view a now-unused cell with the given identifier.
cell = (uploadCustomCell *)[tableView dequeueReusableCellWithIdentifier:#"uploadCustomCell"];
if (cell == nil) {
NSLog(#"cell allocated");
// Use the default cell style.
cell = [[uploadCustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"uploadCustomCell"];
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"uploadCustomCell"
owner:self options:nil];
cell = [nib objectAtIndex:0];
}
saveBtnCcell.hidden = YES;
cell.textNamefield.hidden = YES;
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
[cell.defaultSwitch setEnabled:NO];
dictionaryContents = [contents objectAtIndex:indexPath.row];
NSLog(#"dict dict :%#",dictionaryContents);
//
cell
.nameLabelCell.text = [dictionaryContents valueForKey:#"VideoName"];
cell.userName.text = [dictionaryContents valueForKey:#"User"];
NSLog(#"Array Image:%#",arrayimage);
cell.thumbImg.image = [arrayimage objectAtIndex:indexPath.row];
NSLog(#"ARimage:%#,index%d",[arrayimage objectAtIndex:indexPath.row],indexPath.row);
NSString *defaultVideo = [dictionaryContents valueForKey:#"DefaultVideo"];
NSLog(#"Default Video:%#",defaultVideo);
if ([defaultVideo isEqual: #"1"]) {
// [cell.defaultSwitch setOn:YES animated:YES];
[defaultSwitche setOn:YES animated:YES];
}
else{
// [cell.defaultSwitch setOn:NO animated:YES];
[defaultSwitche setOn:NO animated:YES];
}
[cell.defaultSwitch addTarget:self action:#selector(setState:) forControlEvents:UIControlEventValueChanged];
VideoNameTextField.hidden = YES;
return cell;
}
// Code in customcell
#interface uploadCustomCell (){
UploadAllViewController *uploadAll;
}
#end
#implementation uploadCustomCell
#synthesize textNamefield;
#synthesize savebtn,edit,nameLabelCell,textLabel,uploadBTN;
#synthesize defaultSwitch;
//#synthesize uploadAll;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)dealloc {
[_userName release];
[_thumbImg release];
//[savebtn release];
[textNamefield release];
[nameLabelCell release];
[_test release];
[savebtn release];
[defaultSwitch release];
[uploadBTN release];
[super dealloc];
}
- (IBAction)editAction:(id)sender {
[uploadBTN setEnabled:NO];
uploadAll = [[UploadAllViewController alloc]init];
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:uploadAll.tabelView1];
NSIndexPath *indexPath = [uploadAll.tabelView1 indexPathForRowAtPoint:buttonPosition];
int no = indexPath.row;
NSLog(#"index path :%d",no);
[uploadAll didEditButtonPressed:self];
}
- (IBAction)saveBtnAction:(id)sender {
[uploadBTN setEnabled:YES];
[uploadAll didSaveButtonPressed:self];
}
when i select this editAction: except that cell remaining cells should be grayouted.
In your cellForRowAtIndexPath you have to account for the state of your table view, i.e. if one or zero cells are selected. Use that to change the appearance of your cell as you wish. In the example below I have assumed you are having a straight array without any sections, but the same principle would work with indexPaths as well. I use an int selectedRow set to -1 if there is no cell selected.
#define kNoCellSelected -1
// in cellForRowAtIndexPath:
if (self.selectedRow == kNoCellSelected) {
cell.backgroundView.backgroundColor = normalColor;
cell.userInteractionEnabled = YES;
}
else if (self.selectedRow != indexPath.row) {
cell.backgroundView.backgroundColor = disabledColor;
cell.userInteractionEnabled = NO;
}
Don't forget to set selectedRow in didSelectRowAtIndexPath: and in viewDidLoad.

I want to save everything in a UITableView controller, with a button

I want to save everything in a UITableView controller, with a button, I dont know how to do that. I know it has a saving method, but when you press back to the homescreen of the app, and go back to the viewcontroller, the text is gone, or when i deleted something its still there.
code in my .m file
#import "HomeWorkViewController.h"
#interface HomeWorkViewController ()
#end
#implementation HomeWorkViewController
#synthesize adView;
#synthesize myTableView, numbers;
-(void) viewDidLoad
{
adView.delegate=self;
[super viewDidLoad];
self.navigationItem.leftBarButtonItem = self.editButtonItem;
// check here if key exists in the defaults or not, if yes the retrieve results in array
if([[NSUserDefaults standardUserDefaults] objectForKey:#"numberArray"] != nil) {
self.numbers = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:#"numberArray"]];
}
//Register for the notification when user go to background or minimize the app, just save the array objects in the defaults
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(appWillGoToBackground:)
name:UIApplicationWillResignActiveNotification object:[UIApplication sharedApplication]];
//Add the Add button
UIBarButtonItem * addButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target: self action: #selector(insertNewObject)];
self.navigationItem.rightBarButtonItem = addButton;
}
-(void)setEditing:(BOOL)editing animated:(BOOL)animated {
[super setEditing:editing animated:animated];
[self.myTableView setEditing:editing animated:animated];
}
-(void)appWillGoToBackground:(NSNotification *)note {
NSLog(#"terminate");
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults setObject:self.numbers forKey:#"numberArray"];
[defaults synchronize];
}
-(void)insertNewObject{
//Display a UIAlertView
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Enter HomeWork" message: #"" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
//Only perform the following actions if the user hits the ok button
if (buttonIndex == 1)
{
NSString * tmpTextField = [alertView textFieldAtIndex:0].text;
if(!self. numbers){
self.numbers = [[NSMutableArray alloc]init];
}
[self.numbers insertObject:tmpTextField atIndex:0];
NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.myTableView insertRowsAtIndexPaths:#[indexPath]withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.numbers.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.textLabel.text = [self.numbers objectAtIndex:indexPath.row];
return cell;
}
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
//remove our NSMutableArray
[self.numbers removeObjectAtIndex:indexPath.row];
//remove from our tableView
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath
toIndexPath:(NSIndexPath *)toIndexPath
{
}
-(void)bannerViewDidLoadAd:(ADBannerView *)banner
{
adView.hidden=FALSE;
NSLog(#"Has ad, showing");
}
-(void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
{
adView.hidden=TRUE;
NSLog(#"Has no ads, hiding");
}
-(void)dealloc
{
[adView release];
[super dealloc];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
#end
Looks like you are only saving your data when the application enters the background. If you want to persist the data immediately instead of just when the app closes, just write your array to NSUserDefaults in alertView:clickedButtonAtIndex:

Xcode how to link UITableView Cells to a new View Controller

I currently have developed a Tabbed Based Application. The first Tab is decors which displays Colour Swatches or Images in a TableView Structure. Currently when you push on a image or Colour swatch An alert pops up saying which table cell you have pushed. I instead want to link each table cell image or Colour swatch to a new view controller showing a bigger image of that image or colour swatch. A modal would also do fine
#import "TableViewsViewController.h"
#implementation TableViewsViewController
#pragma mark -
#pragma mark Synthesizers
#synthesize table;
#synthesize sitesArray;
#synthesize imagesArray;
#pragma mark -
#pragma mark View lifecycle
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
// Load up the sitesArray with a dummy array : sites
NSArray *sites = [[NSArray alloc] initWithObjects:#"a", #"b", #"c", #"d", #"e", #"f", #"g", #"h", nil];
self.sitesArray = sites;
[sites release];
UIImage *active = [UIImage imageNamed:#"a.png"];
UIImage *ae = [UIImage imageNamed:#"b.png"];
UIImage *audio = [UIImage imageNamed:#"c.png"];
UIImage *mobile = [UIImage imageNamed:#"d.png"];
UIImage *net = [UIImage imageNamed:#"e.png"];
UIImage *photo = [UIImage imageNamed:#"f.png"];
UIImage *psd = [UIImage imageNamed:#"g.png"];
UIImage *vector = [UIImage imageNamed:#"h.png"];
NSArray *images = [[NSArray alloc] initWithObjects: active, ae, audio, mobile, net, photo, psd, vector, nil];
self.imagesArray = images;
[images release];
[super viewDidLoad];
}
#pragma mark -
#pragma mark Table View datasource methods
// Required Methods
// Return the number of rows in a section
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
return [sitesArray count];
}
// Returns cell to render for each row
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
// Configure cell
NSUInteger row = [indexPath row];
// Sets the text for the cell
//cell.textLabel.text = [sitesArray objectAtIndex:row];
// Sets the imageview for the cell
cell.imageView.image = [imagesArray objectAtIndex:row];
// Sets the accessory for the cell
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
// Sets the detailtext for the cell (subtitle)
//cell.detailTextLabel.text = [NSString stringWithFormat:#"This is row: %i", row + 1];
return cell;
}
// Optional
// Returns the number of section in a table view
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
#pragma mark -
#pragma mark Table View delegate methods
// Return the height for each cell
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 78;
}
// Sets the title for header in the tableview
-(NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return #"Decors";
}
// Sets the title for footer
-(NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
return #"Decors";
}
// Sets the indentation for rows
-(NSInteger) tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 0;
}
// This method is run when the user taps the row in the tableview
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Tapped row!"
message:[NSString stringWithFormat:#"You tapped: %#", [sitesArray objectAtIndex:indexPath.row]]
delegate:nil
cancelButtonTitle:#"Yes, I did!"
otherButtonTitles:nil];
[alert show];
[alert release];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning {
NSLog(#"Memory Warning!");
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
self.table = nil;
self.sitesArray = nil;
self.imagesArray = nil;
[super viewDidUnload];
}
- (void)dealloc {
[table release];
[sitesArray release];
[imagesArray release];
[super dealloc];
}
#end
Part where the Alert is
// This method is run when the user taps the row in the tableview
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Tapped row!"
message:[NSString stringWithFormat:#"You tapped: %#", [sitesArray objectAtIndex:indexPath.row]]
delegate:nil
cancelButtonTitle:#"Yes, I did!"
otherButtonTitles:nil];
[alert show];
[alert release];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
In didSelectRowAtIndexPath you can just init another view controller and present. You can present it from self.navigationController so that there is a back button if you wish. Here I show it presented modally:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Deselect row
[tableView deselectRowAtIndexPath:indexPath animated:YES];
// Declare the view controller
UIViewController *anotherVC = nil;
// Determine the row/section on the tapped cell
switch (indexPath.section) {
case 0:
switch (indexPath.row) {
case 0: {
// initialize and allocate a specific view controller for section 0 row 0
anotherVC = [[ViewControllerForRowZeroSectionZero alloc] init];
break;
}
case 1: {
// initialize and allocate a specific view controller for section 0 row 1
anotherVC = [[ViewControllerForRowOneSectionZero alloc] init];
break;
}
}
break;
case 1: {
// initialize and allocate a specific view controller for section 1 ALL rows
anotherVC = [[ViewControllerForAllRowsSectionOne alloc] init];
break;
}
}
// Get cell textLabel string to use in new view controller title
NSString *cellTitleText = [[[tableView cellForRowAtIndexPath:indexPath] textLabel] text];
// Get object at the tapped cell index from table data source array to display in title
id tappedObj = [sitesArray objectAtIndex:indexPath.row];
// Set title indicating what row/section was tapped
[anotherVC setTitle:[NSString stringWithFormat:#"You tapped section: %d - row: %d - Cell Text: %# - Sites: %#", indexPath.section, indexPath.row, cellTitleText, tappedObj]];
// present it modally (not necessary, but sometimes looks better then pushing it onto the stack - depending on your App)
[anotherVC setModalPresentationStyle:UIModalPresentationFormSheet];
// Have the transition do a horizontal flip - my personal fav
[anotherVC setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
// The method `presentModalViewController:animated:` is depreciated in iOS 6 so use `presentViewController:animated:completion:` instead.
[self.navigationController presentViewController:anotherVC animated:YES completion:NULL];
// We are done with the view controller. It is retained by self.navigationController so we can release it (if not using ARC)
[anotherVC release], anotherVC = nil;
}
You're 90% of the way there! In didSelectRowAtIndexPath, instead of putting up the alert, instantiate and set up the view controller whose view you want to show and call presentViewController:animated:.
See my book: http://www.apeth.com/iOSBook/ch19.html#_presented_view_controller
Are u using Storyboard?
If so, you can build a segue, set it to Modal or Push. Pointing from the TableView to the destination ViewController
Then name it with an identifier in the segue's inspector.
Then in didSelectRowAtIndexPath, call performSegue: withIdentifier
You can also setup the destination ViewController based on the cell selected in prepareForSegue.
Hope it helps.

Need Help Deleting Data From UITableView

I am trying to make my UITableView Editable but I'm having some trouble with the code, specifically with the commitEditingStyle method. It is not working I think the method I have is only for plist and not for an array by itself.
#import "RoutineTableViewController.h"
#import "AlertPrompt.h"
#implementation RoutineTableViewController
#synthesize myArray;
- (void)dealloc
{
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
myArray = [[NSMutableArray alloc] init];
myData = [[NSMutableArray arrayWithContentsOfFile:#"mydata"] retain];
if (myData == nil)
{
myData = [NSMutableArray array];
}
[super viewDidLoad];
UIBarButtonItem * addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(showPrompt)];
[self.navigationItem setLeftBarButtonItem:addButton];
[addButton release];
self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
-(void)showPrompt
{
AlertPrompt *prompt = [AlertPrompt alloc];
prompt = [prompt initWithTitle:#"Add Workout Day" message:#"\n \n Please enter title for workout day" delegate:self cancelButtonTitle:#"Cancel" okButtonTitle:#"Add"];
[prompt show];
[prompt release];
}
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (buttonIndex != [alertView cancelButtonIndex])
{
NSString *entered = [(AlertPrompt *)alertView enteredText];
NSLog([NSString stringWithFormat:#"%#", entered]);
if(myData && entered)
{
[myArray addObject:entered];
[tableView reloadData];
}
}
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [myArray 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] autorelease];
}
cell.textLabel.text = [self.myArray objectAtIndex:indexPath.row];
return cell;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = [indexPath row];
[self.list removeObjectAtIndex:row];
[tableView deleteRowsAtIndexPaths:[myArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
As prevoulsy ansewered; self.list has to be Mutable.
The next thing you need to do is "warn" the tableView about the updates.
So you would do it like this:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = [indexPath row];
[self.list removeObjectAtIndex:row];
//Notice we "warn" the tableView
[tableView beginUpdates];
[tableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
//We also tell the table the updates are done so it can do the proper animations
[tableView endUpdates];
}
Remember you first change the model and then update the tableView with the add, reload and delete methods in between a beginUpdates and endUpdates.
What type is self.list? It needs to be an NSMutableArray for a call to 'removeObjectAtIndex' to be valid.
There is no .plist involved here, that's just the name of this NSMutableArray. Your sample code assumes you are declaring an NSMutableArray called list in your #interface...
#interface RoutineTableViewController : UIViewController {
NSMutableArray *list;
}
#property (nonatomic, retain) NSMutableArray *list;
#end
... and synthesizing it (and filling it with something) somewhere in your code.

Table View alert does not show

I have the following code in a UITableViewController:
#import "TaskTableController.h"
#implementation TaskTableController
- (void)viewDidLoad {
theArray = [[NSArray alloc] initWithObjects:#"Apple",#"Pineapple",#"Banana",nil];
[super viewDidLoad];
}
- (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 [theArray 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] autorelease];
}
cell.textLabel.text = [theArray objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Selected a row" message:[theArray objectAtIndex:indexPath.row] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
- (void)dealloc {
[theArray release];
[super dealloc];
}
#end
The problem is when I click on a cell, it highlights the cell but does not ever show the alert. Is there something that I am missing? Inside FirstView I have a tableview the tableview looks at the tableview object that's class is set to TaskTableController.
I think you forget to set delegate UITableViewDelegate with FileOwner.