使用Xcode 6和OBJ C设置委派

时间:2015-02-22 21:39:06

标签: ios objective-c xcode

我正式陷入困境。我试图从一个视图控制器发送数据(NSString)到另一个。我相信我已经准备好了一切,但它并没有奏效。我做了一个示例应用程序来测试。如果有人能看到并提出建议,我将非常感激。

示例应用有2个视图控制器。 VC1有一个简单的UITextView。 VC2有一个UITextField。通过按VC1上的按钮,VC2以模态方式显示。然后,用户可以将数据输入VC2,当按下关闭按钮时,数据应填充VC1中的文本视图。问题是这不起作用。

感谢您的关注。

VC1.h

#import <UIKit/UIKit.h>
#import "ViewController2.h"

@interface ViewController : UIViewController <ViewController2Delegate>

@property (weak, nonatomic) IBOutlet UITextView *mainTextView;

@end

VC1.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dataForMainViewSet:(ViewController2 *)sender dataToSet:(id)data {
    self.mainTextView.text = data;
}
@end

VC2.h

#import <UIKit/UIKit.h>

@class ViewController2;

@protocol ViewController2Delegate <NSObject>

@optional
- (void)dataForMainViewSet:(ViewController2 *)sender dataToSet:(id)data;
@end

@interface ViewController2 : UIViewController
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) id <ViewController2Delegate> delegate;

- (IBAction)closeVC2;
@end

VC2.m

#import "ViewController2.h"
#import "ViewController.h"

@interface ViewController2 () <UITextFieldDelegate>

@end

@implementation ViewController2

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.textField.delegate = self;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)closeVC2 {
    [self.delegate dataForMainViewSet:self
                            dataToSet:self.textField.text];

    [self dismissViewControllerAnimated:YES completion:nil];
}
@end

1 个答案:

答案 0 :(得分:0)

感谢大家的评论和帮助。 @ Kilogen9你激起了我的记忆,我记得我错过了什么。

我在导航控制器中嵌入了VC2。然后在VC1中我添加了一个prepareForSegue,在segue之前,我将VC2.delegate设置为self。

我离开编码差不多一年了,并且坐在这里看着我真实项目中的代码至少一周,试图找出我忘记的步骤。 Stack Overflow社区再次帮助。

谢谢!