在iOS頁面間傳值詳解(一)中凉唐,介紹了iOS界面間的正向傳值以及逆向傳值的兩種方法,其實逆向傳值還可以使用block和KVO等方式霍骄,下面介紹這兩種傳值方式台囱。
情景回顧
有兩個界面,ViewControllerA和ViewControllerB,在ViewControllerA中有一個label和跳轉(zhuǎn)到B界面的一個按鈕读整,在ViewControllerB中有一個textField和返回A界面的按鈕玄坦,需要將B界面中textField上屬于的值顯示在A界面的label上。
1.block逆向傳值
- 步驟一:B界面定義一個block并聲明一個屬性
typedef void (^valueBlock) (NSString *strValue);
// 聲明屬性
@property (nonatomic, copy) valueBlock valueBlock;
- 步驟二:在B界面返回A界面的地方绘沉,把需要返回的值給block的參數(shù)
- (void)buttonClick {
__weak typeof(self) weakSelf = self;
if (weakSelf.valueBlock) {
weakSelf.valueBlock(weakSelf.textField.text);
}
[self.navigationController popViewControllerAnimated:YES];
}
- 步驟三:在A界面回調(diào)block
- (void)buttonClick {
ViewControllerB *VC = [[ViewControllerB alloc] init];
VC.valueBlock = ^(NSString *strValue) {
self.label.text = strValue;
};
[self.navigationController pushViewController:VC animated:YES];
}
2.KVO方式傳值
- 步驟一:在A界面中定義屬性并在A界面跳轉(zhuǎn)B界面的方法中添加觀察者
// 添加屬性
@property (nonatomic, strong) ViewControllerB *viewControllerB;
- (void)buttonClick {
self.viewControllerB = [[ViewControllerB alloc] init];
[self.viewControllerB addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew context:nil];
[self.navigationController pushViewController:self.viewControllerB animated:YES];
}
- 步驟二:在A界面中實現(xiàn)監(jiān)聽對應(yīng)Key值變化的方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
if ([keyPath isEqualToString:@"text"]) {
self.label.text = self.viewControllerB.text;
}
}
- 步驟三:在B界面返回A界面的方法中煎楣,將值賦給對應(yīng)的屬性
// 在.h文件中設(shè)置對應(yīng)的屬性
@property (nonatomic, strong) NSString *text;
// 賦值
- (void)buttonClick {
self.text = self.textField.text;
[self.navigationController popViewControllerAnimated:YES];
}