I have 2 ViewControllers, in 1st – TableView and in 2nd – button with label on it. When I click on the button in 2nd ViewController I need to go back on TableView and set in
cell.detailTextLabel.text
text from label on the button.
Here is my code, but it does not work:
ViewController.h:
#import <UIKit/UIKit.h>
#import "TestControl.h"
@interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, myTestProtocol>
{
TestControl *myProtocol;
}
@property (strong, nonatomic) IBOutlet UITableView * tableTest;
@end
ViewController.m:
#import "ViewController.h"
#import "TestControl.h"
@implementation ViewController
@synthesize tableTest;
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationController.navigationBarHidden = YES;
myProtocol = [[TestControl alloc]init];
myProtocol.delegate = self;
// Do any additional setup after loading the view, typically from a nib.
}
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 3;
}
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
TestControl * test = [[TestControl alloc] initWithNibName:@"TestControl" bundle:nil];
[self.navigationController pushViewController:test animated:YES];
}
- (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];
}
switch (indexPath.row) {
case 0:
cell.textLabel.text = @"Firs Cell";
cell.detailTextLabel.text = myProtocol.myLabel.text;
break;
case 1:
cell.textLabel.text = @"Second Cell";
break;
case 2:
cell.textLabel.text = @"Third Cell";
break;
default:
break;
}
return cell;
}
@end
TestControl.h:
#import <UIKit/UIKit.h>
@protocol myTestProtocol <NSObject>
@end
@interface TestControl : UIViewController
{
UILabel *myLabel;
}
@property (nonatomic, assign) id <myTestProtocol> delegate;
@property (strong, nonatomic) IBOutlet UILabel *myLabel;
- (IBAction)testButton:(id)sender;
@end
TestControl.m:
@implementation TestControl
@synthesize myLabel;
@synthesize delegate;
- (IBAction)testButton:(id)sender
{
myLabel.text = @"TEXT LABEL";
[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:0] animated:YES];
}
What is the problem in this???
A couple of things….
You are creating two different
TestControlobjects, setting the delegate for one of them and pushing the other one, so the one handling the button tap has no delegate.The delegate logic would work better the other way around. That is,
TestControlshould have the code that communicates with its delegate rather than the delegate “pulling” fromTestControl.