说我view1
上的标签连接到ViewController1.m
。我希望能够在名为label.text
的其他视图控制器中更改ViewController2.m
值。
首先,我尝试将标签(已连接到ViewController1.m
)连接到ViewController2.m
,但它不允许我将其作为插座连接,只是一个操作。可能是因为引用的类是ViewController1
。
答案 0 :(得分:0)
要直接回答您的问题,假设您是故事板或xib,您只能将插座连接到与"自定义中定义的同一类或子类的viewController类"对于那个viewController。
但是,这非常重要,不要将连接与实例化混淆。让我们说你实际上连接了viewController1.textField和viewController2.textField,这并不意味着当viewController2出现时,viewController2.textField将神奇地拥有viewController1.textField中的值。也不会更新viewController2.textField将该值反映回viewController1.textField。您必须手动执行此操作,因为连接是相对于viewController的单个给定实例。
假设首先显示ViewController1,则双向通信如下:
如果您是故事板,则需要在prepareForSegue中将值从一个viewController传递到另一个viewController,例如:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// NOTE: if your viewController is laid out with multiple segues,
// use [segue identifier] to discern which segue has been triggered
ViewController2 *vc = (ViewController2 *)[segue destinationViewController];
vc.textField = self.textField;
}
如果您要实例化而不是故事板(警告:此代码尚未经过测试):
ViewController2 *vc = [[ViewController2 alloc] init];
vc.textField = self.textField;
[self presentViewController: vc animated: YES];
如果要将某些内容从viewController2传递回viewController1,那么您将创建一个协议,将viewController1设置为viewController2的委托,然后根据需要回调以镜像该值。
ViewController1.h:
#import "ViewController2.h"
@interface ViewController1 : UIViewController<ViewController2Delegate>
ViewController1.m:
vc.delegate = self; // vc = pointer to viewController2
ViewController2.h:
@protocol ViewController2Delegate<NSObject>
@required
- (void)importantValueDidChange:(NSString *)value;
@end
@property (weak, nonatomic) id<ViewController2Delegate> delegate;
ViewController2.m :(当值需要更新时)
if([self.delegate respondsToSelector: @selector(@ importantValueDidChange:)]) {
[self.delegate importantValueDidChange: self.textField.text];
}