在oc 中,反向傳值可以采用block塊來實現,同樣,在swift 中也有類似的閉包,下面就閉包傳值進行簡單的介紹。
這里兩個界面的基本邏輯是這樣的:
(點擊 “下一頁”,進入下一頁b),點擊b中的按鈕,按鈕的文字會顯示在a的label上。
a界面:b界面:傳值后的a界面:
b->a:那么就應該在b中聲明閉包,a中定義閉包,并賦值給b,然后調用:
b中閉包聲明:
varclosure:((title:String)->Void)!
a中閉包定義:
letsecondVC:SecondViewController=SecondViewController()
secondVC.closure= {(title:String)in
self.buttonLabel.text= title}
閉包調用:
@IBActionfuncbuttonClicked(sender:UIButton) {
lettitle = sender.currentTitle
self.closure(title: title!)
self.dismissViewControllerAnimated(true, completion:nil)
}
這就實現了簡單的回調,閉包傳值。