Я дам вам образец кодирования. Настройте приведенный ниже код.
Здесь у нас есть два контроллера вида.
ViewController и SecondViewController
в SecondViewController
.h
#import <UIKit/UIKit.h>
@class SecondViewController;
@protocol SecondViewControllerDelegate <NSObject>
- (void)secondViewController:(SecondViewController *)secondViewController didEnterText:(NSString *)text;
@end
@interface SecondViewController : UIViewController
@property (nonatomic, assign)id<SecondViewControllerDelegate> delegate;
@property (nonatomic, strong) IBOutlet UITextField *nameTextField;//It must connect as outlet connection
- (IBAction)doneButtonTapped:(id)sender;
@end
.m
#import "SecondViewController.h"
@interface SecondViewController()
@end
@implementation SecondViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
//Either use NSNotification or Delegate
- (IBAction)doneButtonTapped:(id)sender;
{
//Use Notification
[[NSNotificationCenter defaultCenter] postNotificationName:@"passingDataFromSecondViewToFirstView" object:self.nameTextField.text];
//OR Custom Delegate
[self.delegate secondViewController:self didEnterText:self.nameTextField.text];
[self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
в ViewController
.h
#import <UIKit/UIKit.h>
#import "SecondViewController.h"
@interface ViewController : UIViewController<SecondViewControllerDelegate>
@property (nonatomic, strong) IBOutlet UILabel *labelName; //You must connect the label with outlet connection
- (IBAction)gotoNextView:(id)sender;
@end
.m
#import "ViewController.h"
@interface ViewController()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//addObserver here...
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFromPreviousViewControllerNotificationReceived:) name:@"passingDataFromSecondViewToFirstView" object:nil];
// Do any additional setup after loading the view, typically from a nib.
}
//addObserver Method here....
- (void)textFromPreviousViewControllerNotificationReceived:(NSNotification *)notification
{
// set text to label...
NSString *string = [notification object];
self.labelName.text = string;
}
- (IBAction)gotoNextView:(id)sender;
{
//If you use storyboard
SecondViewController *secondViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondViewController"];
//OR If you use XIB
SecondViewController *secondViewController = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];
secondViewController.delegate = self;
[self.navigationController pushViewController:secondViewController animated:YES];
}
//Calling custom delegate method
- (void)secondViewController:(SecondViewController *)secondViewController didEnterText:(NSString *)text
{
self.labelName.text = text; //Getting the data and assign the data to label here.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
Для вашего понимания кода я создаю простой передачи данных из одного второго контроллера представления на первый контроллер представления.
Сначала мы перемещаем представление от контроллера первого взгляда до второго контроллера.
После этого мы отправляем данные с контроллера второго вида на контроллер первого вида.
Примечание: Вы можете использовать метод NSNotification или пользовательский делегат для передачи данных от одного View Controller для другого View Controller
Если вы используете NSNotification, вам необходимо установить postNotificationName для получения данных в кнопке способ действия.
Далее вам нужно написать addObserver (отправка данных в требуемый контроллер просмотра) ViewController и вызов метода addObserver в том же контроле View.
Если вы используете пользовательский делегат, Обычно мы идем с пользовательского протокола делегатом, а также мы должны Присвоить делегат здесь.
Очень важно, мы должны установить пользовательский делегат метода в Второй View Controller .because где мы отправляем данные в первый контроллер представления один раз кликаем кнопку Готово во втором контроллере представления.
Наконец, мы должны вызвать пользовательский делегат метода в First View Controller, где мы получаем данные и назначить эти данные для label.Now вы можете увидеть передаваемые данные, используя пользовательский делегат.
Аналогично вы можете отправить данные в другой контроллер представления с использованием пользовательского делегат Методы
Вы толкание/представляя свой 'CustomController' где-нибудь? – Vijay
Вы уверены, что вызывается 'viewDidLoad'? Откуда вы знаете? – Arc676
попробовать контрольную точку внутри 'didDataRecieved' – abhi1992