【发布时间】:2014-06-15 19:03:03
【问题描述】:
所以我正在尝试掌握使用委托的技巧,到目前为止,我已经观看了一些关于如何使用委托的教程。我仍然觉得它们令人困惑,并且在尝试自己实现一个之后,有一个我似乎无法解决的问题。
我有两个 ViewController,第一个 ViewController 包含一个 UITextField *sampleTextField 和一个带有方法 switchViews 的按钮。它还包含带有sendTextToViewController 方法的协议声明。 SwitchViews 还链接到切换到SecondViewController 的segue。在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];
}
I've looked at this 和第一个答案是有道理的,但由于某种原因它不起作用。
我确实认为问题出在我设置调用[vc setDelegate:self] 的位置,但不知道如何解决这个问题。一些正确方向的指针将不胜感激。请记住,我是 obj-c 的新手,所以如果你能解释你在说什么,那就太好了。谢谢。
【问题讨论】:
标签: ios iphone objective-c delegates