我正在尝试将SecondViewController指定为FirstViewController的委托对象(如果我理解正确的话)。但是,FirstViewController不会向SecondViewController发送任何消息。
我是否可以假装SecondViewController确实从FirstViewController获取消息并响应FirstViewController? (注意:我的SecondViewController负责一个带按钮的视图。当我按下SecondViewController视图上的按钮时,我希望它告诉FirstViewController更新其视图)
FirstViewController.h
#import <UIKit/UIKit.h>
@protocol FirstViewControllerDelegate <NSObject>
@optional
- (void) setAnotherLabel;
@end
@interface FirstViewController : UIViewController {
IBOutlet UILabel *label;
id <FirstViewControllerDelegate> delegate;
}
@property (nonatomic, retain) IBOutlet UILabel *label;
@property (nonatomic, assign) id <FirstViewControllerDelegate> delegate;
- (void) pretendLabel;
- (void) realLabel;
@end
FirstViewController.m
#import "FirstViewController.h"
@implementation FirstViewController
@synthesize label;
@synthesize delegate;
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void) setAnotherLabel;
{
label.text =@"Real";
[self.view setNeedsDisplay];
}
- (void) pretendLabel;
{
label.text =@"Pretend";
[self.view setNeedsDisplay];
}
- (void) realLabel;
{
[self setAnotherLabel];
}
- (void)viewDidLoad
{
[super viewDidLoad];
label.text=@"Load";
[self pretendLabel];
}
...
@end
SecondViewController.h
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "FirstViewController.h"
@interface SecondViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate, FirstViewControllerDelegate>
{
UIImage *image;
IBOutlet UIImageView *imageView;
}
- (IBAction) sendPressed:(UIButton *)sender;
- (IBAction) cancelPressed:(UIButton *)sender;
@end
SecondViewController.m
#import "SecondViewController.h"
@implementation SecondViewController
- (IBAction) sendPressed:(UIButton *)sender
{
FirstViewController *fvc = [[FirstViewController alloc] init];
[fvc setDelegate:self];
//how do I find out if I'm actually the delegate for FirstViewController at this point?
[fvc realLabel];
self.tabBarController.selectedIndex = 0;//switch over to the first view to see if it worked
}
答案 0 :(得分:1)
这有一些问题,看起来有些混乱。
我假设FirstViewController和SecondViewController位于标签栏控制器的单独选项卡中。
在sendPressed:
方法中,您正在创建FirstViewController的新实例 - 这与标签栏控制器中的FirstViewController不同,以及为什么调用realLabel
无效。
第二点是您似乎误解了委托的工作方式 - 您发布的代码中没有委托代理。
至于问题的解决方案,有几个选择:
- (IBAction) sendPressed:(UIButton *)sender
{
for(UIViewController *controller in self.tabBarController.viewControllers)
{
if([controller isKindOfClass:[FirstViewController class]])
{
FirstViewController *firstViewController = (FirstViewController *)controller;
[firstViewController realLabel];
}
}
self.tabBarController.selectedIndex = 0;//switch over to the first view to see if it worked
}
有比这更多的选项,但上面的内容将为您提供一个良好的开端,为您的需求研究最佳方法。
希望这有帮助。