Question

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.

Was it helpful?

Solution

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


OTHER TIPS

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
    
              }
       }
    

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)

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top