[英]Delegate method not being called, setting delegate to self?
因此,我試圖擺脫使用委托的束縛,到目前為止,我已經看了一些有關如何使用委托的教程。 我仍然發現它們令人困惑,並且在嘗試自己實施后,遇到了一個我似乎無法解決的問題。
我有兩個ViewController,第一個ViewController
包含一個UITextField *sampleTextField
和一個帶有switchViews
方法的按鈕。 它還包含帶有sendTextToViewController
方法的協議聲明。 SwitchViews
也鏈接到切換到SecondViewController
。 在SecondViewController
的唯一對象是一個UILabel *outputLabel
當用戶點擊該按鈕,它調用switchViews
和視圖改變SecondViewController,並在加載outputLabel
應改為無論在文字輸入了sampleTextField
在ViewController
。 但是,永遠不會調用委托方法sendTextToViewController
。 所有對象都在Interface Builder中創建。
這是使它更容易理解的代碼:
ViewController.h
#import <UIKit/UIKit.h>
@protocol TextDelegate <NSObject>
-(void)sendTextToViewController:(NSString *)stringText;
@end
@interface ViewController : UIViewController
- (IBAction)switchViews:(id)sender;
@property (weak, nonatomic) IBOutlet UITextField *sampleTextField;
@property (weak, nonatomic) id<TextDelegate>delegate;
@end
然后在ViewController.m中聲明
- (IBAction)switchViews:(id)sender {
NSLog(@"%@", self.sampleTextField.text);
[self.delegate sendTextToViewController:self.sampleTextField.text];
}
SecondViewController.h
#import <UIKit/UIKit.h>
#import "ViewController.h"
@interface SecondViewController : UIViewController <TextDelegate>
@property (weak, nonatomic) IBOutlet UILabel *outputLabel;
@end
SecondViewController.m
#import "SecondViewController.h"
@interface SecondViewController ()
@end
@implementation SecondViewController
@synthesize outputLabel;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
ViewController *vc = [[ViewController alloc]init];
[vc setDelegate:self];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)sendTextToViewController:(NSString *)stringText
{
NSLog(@"Sent text to vc");
[outputLabel setText:stringText];
}
我已經看過了 ,第一個答案是有道理的,但是由於某些原因,它沒有用。
我確實認為問題出在我設置調用[vc setDelegate:self]
,但不確定如何解決此問題。 朝正確方向的一些指針將不勝感激。 請記住,我是obj-c的新手,所以如果您可以解釋自己的意思,那將很棒。 謝謝。
您正在創建ViewController
的新實例,但是對此不做任何事情。
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
ViewController *vc = [[ViewController alloc]init];
[vc setDelegate:self];
}
SecondViewController
需要引用FirstViewController
才能將其自身設置為委托。
首先,您不必使用委托來執行這樣的程序。 一種更簡單的方法是在SecondViewController中創建一個屬性,然后將textField的內容傳遞給該屬性。
您的代碼無效,因為您在尚未設置的委托上調用了sendTextToViewController。 您已將委托設置為ViewController的新實例,而不是屏幕上顯示的實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.