2

Main Screen

Table View select specific Row and save that row

Show specific row contents on the main screen

Plz code Help Can anyone tell me how to do that task? In main screen user selects footballer,in 2nd screen in Table view cell user select specific row and save that row and go back to main view.in main view then it shows the specific row videos. Basically i want to know about speific row selection,save that selection in table view and show thier contetnts in main screen.

user2396021
  • 85
  • 2
  • 8
  • 3
    Study a little bit about delegation. – Bourne Nov 13 '13 at 06:20
  • @Bourne I would have given you more UP's if only possible. :P – Dunes Buggy Nov 13 '13 at 06:21
  • For get selected row's data in first view controller you need to create protocol..http://stackoverflow.com/questions/626898/how-do-i-create-delegates-in-objective-c and http://stackoverflow.com/questions/5244830/using-a-delegate-to-pass-data-back-up-the-navigation-stack – iPatel Nov 13 '13 at 06:21
  • You can use this github repo [JLSelectionTVC](https://github.com/nvrtdfrst/JLSelectionTVC) which accomplishes that – nvrtd frst Apr 15 '14 at 19:14

4 Answers4

1

go through the below code, it implements the delegate concept and also implements the solution for ur question hope this helps u :)


  //in your main view controller

  #import "ViewController.h"
  #import "FootBallPlayersViewController.h"

  @interface ViewController ()<FootballPlayerDelegate>//confirms to this delegate 

  @end

  @implementation ViewController

  - (void)viewDidLoad
   {
        [super viewDidLoad];



// Do any additional setup after loading the view, typically from a nib.
   }

 - (IBAction)whenSelectButtonClicked:(id)sender
   {
        FootBallPlayersViewController *controller = [[FootBallPlayersViewController alloc]initWithNibName:@"FootBallPlayersViewController" bundle:nil];
        controller.delegate = self; //u must set to self
        [self presentViewController:controller animated:YES completion:nil];


   }

  - (void)didReceiveMemoryWarning
  {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
  }

  - (void)selectedFootBallPlayer:(NSString *)player
    {
      //implementation of your delegate method

      //hear u are getting the football player name and u can continue further hear
       NSLog(@"%@",player);
      if([player isEqualToString:@"player1"])
        {
          UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
          [aButton setTitle:player forState:UIControlStateNormal];
          [aButton addTarget:self action:@selector(whenFirstPlayerButtonClicked:) forControlEvents:UIControlEventTouchUpInside]; //add the target to self for click events 
          aButton.frame = CGRectMake(50, 50, 200, 55);
          [self.view addSubview:aButton];

       }
     else
      {
       UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
       [aButton setTitle:player forState:UIControlStateNormal];
       aButton.frame = CGRectMake(50, 105, 200, 55);
        [aButton addTarget:self action:@selector(whenSecondPlayerButtonClicked:) forControlEvents:UIControlEventTouchUpInside]; //same hear
       [self.view addSubview:aButton];

      }


  }
   //now define the action methods 
 - (void)whenFirstPlayerButtonClicked:(UIButton *)sender
  {

       NSLog(@"player 1 video start");    
  }

  - (void)whenSecondPlayerButtonClicked:(UIButton *)sender
  {
       NSLog(@"player 2 video start ");
  }


  @end


in the view that contain's the tableview do somthing like this


//in FootBallPlayersViewController.h

   #import <UIKit/UIKit.h>
     @protocol FootballPlayerDelegate <NSObject>     //define a protocol named      FootballPlayerDelegate
    - (void)selectedFootBallPlayer:(NSString *)player;
    @end

   @interface FootBallPlayersViewController : UIViewController
    {
       NSArray *players;
       NSString *selectedPlayer;
    }

   @property (retain, nonatomic) IBOutlet UITableView *playerTable;
   @property (nonatomic, assign) id<FootballPlayerDelegate>delegate; //create a delegate

   @end


in your FootBallPlayersViewController.m file


   #import "FootBallPlayersViewController.h"

   @interface FootBallPlayersViewController ()<UITableViewDataSource,UITableViewDelegate>
     {


    }
   @end

   @implementation FootBallPlayersViewController
   @synthesize delegate; //synthesizing the delegate

   - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
   {
      self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
      if (self) {
      // Custom initialization
         }
     return self;
    }

    - (void)viewDidLoad
   {
       [super viewDidLoad];
        players = [[NSArray alloc]initWithObjects:@"player1",@"player2", nil];
      // players = [[NSArray alloc]initWithObjects:@"player1","player2", nil];
     // Do any additional setup after loading the view from its nib.
   }

    - (void)didReceiveMemoryWarning
    {
      [super didReceiveMemoryWarning];
     // Dispose of any resources that can be recreated.
    }

   - (void)dealloc
  {
      [players release];
      [_playerTable release];
      [super dealloc];
  }
 - (IBAction)whenDoneButtonClicked:(id)sender {
      //when done button clicked -->
      //send a delegate to main controller
      if([self.delegate respondsToSelector:@selector(selectedFootBallPlayer:)])//to avoid crash
        {
          [self.delegate selectedFootBallPlayer:selectedPlayer]; //call the delegate method hear
        }
     //dismiss the view
     [self dismissViewControllerAnimated:YES completion:nil];

    }


    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
     {
        return 1;
      }

     - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
         return players.count;
    }

     - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
   {

        UITableViewCell *cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"cell"];
        if(cell == nil)
       {
          cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
       }

        cell.textLabel.text = [players objectAtIndex:indexPath.row];
        return cell;
   }

   - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
   {
      //u can manage check mark and all, i am getting the selected player name
     selectedPlayer = [players objectAtIndex:indexPath.row];
    }

 @end


Shankar BS
  • 8,394
  • 6
  • 41
  • 53
0

Simple solution ... As you are a newbie , I am clarifying each point.

  1. First make a property in AppDelegate.h

    @property int selectedRow;

  2. Save the selected indexpath.row in 2nd screen that is your Table view screen, and also import AppDelegate.h

    (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
       {   
         self.appDelegate=(AppDelegate *)[[UIApplication sharedApplication] delegate];
         self.appDelegate.selectedRow=indexPath.row; //saving the row
    
        }
    
  3. On main screen's viewWillAppear()

    -(void)viewWillAppear:(BOOL)animated
      {
         if(self.appDelegate.selectedRow!=-1)//check wether row is selected or not
             {
    
                 //action to show the specific row videos
    
              }
       }
    
Vizllx
  • 9,135
  • 1
  • 41
  • 79
0

Good Ways to accomplish this:

  1. Custom Delegate
  2. NSNotificationCenter
  3. NSUserDefaults (edit: unnecessary disk writes)
  4. Maintaining a Common NSObject Subclass and refreshing data on -willAppear

Other Ways:

  1. Database (Core Data / SQLite) or plist (all too heavy for your case) (edit: unnecessary disk writes)
  2. UIPasteBoard

A quick delegate tutorial:


Part 1: Creating the delegate

Suppose this is in the .h of the UITableViewController subclass that I have named YourTableViewControllerClassName

//declare the protocol
@class YourTableViewControllerClassName;
@protocol YourTableViewControllerClassNameDelegate <NSObject>
//@required    //uncomment to specify required delegate methods as below
//- (void)requiredMethodNotUsedForThisExample;
@optional
- (void)selectedRow: (NSString *)selectedObj;
@end

@interface YourTableViewControllerClassName : UITableViewController
//declare a weak property to store any object
@property (nonatomic, weak) id <YourTableViewControllerClassNameDelegate> delegate;
@end

Suppose this is the -didSelectRowAtIndexPath of the corresponding UITableViewController subclass:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

    //the following line is the main thing and can be called
    //in any method within this class (placed wisely)
    if([[self delegate] respondsToSelector:@selector(selectedRow)]) { //avoid crash
        [[self delegate] selectedRow:cell.textLabel.text];    
    }
    [self.navigationController popViewControllerAnimated:YES];
}

Part 2: Implementing the delegate

Suppose this is the code somewhere in the former UIViewController subclass:

//call this method somewhere
-(void)pushMyTableViewController
{
    //declare "UILabel lblText;" in the .h of this class
    //lblText = [UILabel alloc] init];
    //[lblText setFrame: CGRectMake(0,0,100,35)];
    //[self.view addSubview:lblText];

    YourTableViewControllerClassName *tvcObj = [[YourTableViewControllerClassName alloc] init];
    //for the following line, remember to declare
    //<YourTableViewControllerClassNameDelegate> in the .h of this class
    //hence declaring that this class conforms to the delegate protocol
    [tvcObj setDelegate:self];
    [self.navigationController pushViewController:tvcObj animated:YES];
}

And this will be the delegate method you could implement in the former UIViewController subclass:

#pragma mark - Optional YourTableViewControllerClassName Delegate Methods
-(void)selectedRow:(NSString *)selectedObj
{
    [lblText setText:selectedObj];
}

NOTE: This will not solve your particular issue because we are only setting a label depending on the selected row from the UITableViewController subclass.
The point was to show how delegation works.
Also, if you can get the cell.textLabel.text and set it on a UILabel in the former class then you can make changes at the appropriate places (mainly the method/s within @protocol)and pass the array index of the selected item instead or any object/variable/whatever that makes your life easier

*If you want something easier then go for NSNotificationCenter or NSUserDefaults or maybe even UIPasteBoard (if it floats your boat)

staticVoidMan
  • 19,275
  • 6
  • 69
  • 98
  • i wonder which ghost downvoted me on this. If there are any mistakes, please comment. Also, any improvements or insights will be appreciated (_We're all here to learn and teach, so refrain from demotivating people from answering_). Anyways... i'll keep this around for myself... just incase i ever forget how to make a custom delegate :P – staticVoidMan Nov 16 '13 at 18:16
  • most of the propagated ways are bad. – vikingosegundo Nov 19 '13 at 04:48
  • @vikingosegundo: ok but honestly i don't know enough to know what is bad. some guidance would be greatly appreciated – staticVoidMan Nov 19 '13 at 04:56
  • honestly: it is your answer. if you don't know, what is bad you should investigate it yourself. start with NSUserDefaults. – vikingosegundo Nov 19 '13 at 04:58
  • @vikingosegundo: there are only 6 ways i have mentioned. i am sure you won't like `NSUserDefaults` or `UIPasteBoard` but they do the trick unless you want to make a killer robot. – staticVoidMan Nov 19 '13 at 05:00
  • so just to pass data form one controller to the other you would possibly save data persistently, hit the disk or a database? Curing cancer by shooting the patient also does the trick. – vikingosegundo Nov 19 '13 at 05:17
  • 1 is perfect, 2 is good, 3 is bad, 4 makes no sense, 5 and 6 are some of the dumbest advices I have ever heard of. – vikingosegundo Nov 19 '13 at 05:20
  • @vikingosegundo: haha. i guess i was sliding down with bad ideas. _thanks for your honest opinion_. – staticVoidMan Nov 19 '13 at 05:21
  • You should try to give good or perfect answers — not all answers. – vikingosegundo Nov 19 '13 at 05:22
-1

Use the tableView delegate called when you select any row

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
   appDelegate.selectedindex = indexpath.row;

   or

   [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:indexpath.row] forKey:@"SelcetedIndex"];
}

then there is 3 things you can do to get your selected index

1) make a app delegate variable for index path so that you can set here and get the value on other controller

// add property at appDelegate file @property int selectedIndex;

2) Using NSUserDefault to set the selected index value

// read userDefault value 
[[[NSUserDefaults standardUserDefaults] objectForKey:@"SelcetedIndex"] intValue];

3) using delegate to return back the value to previous controller

// try to google and first understand the concept and let me know if you want to go with delgate

Retro
  • 3,985
  • 2
  • 17
  • 41