下面是一些示例代码,显示了将数据从呈现的视图控制器(VC2)传递到呈现的视图控制器(VC1)的一种方法.
VC2定义了var callback: (() -> Void)?
,这是一种函数类型.它定义了一个没有参数且不返回任何内容的函数.VC1中的Prepare(for Segue:)将回调函数作为代码块提供给VC2.该回调更新Vc1‘S数据,并重新加载Vc1’S表视图.
在VC2中,当 Select Done时,它会在解除之前调用回调函数.
class VC1: UIViewController, UITableViewDataSource {
var data = [1, 2, 3, 4, 5, 6, 7]
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
}
// MARK: - TableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = "\(data[indexPath.row])"
return cell
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Show Number" {
if let cell = sender as? UITableViewCell {
let indexPath = tableView.indexPath(for: cell)
if let vc2 = segue.destination as? VC2 {
vc2.number = data[indexPath!.row]
vc2.callback = {
self.data[indexPath!.row] = vc2.number
self.tableView.reloadData()
}
}
}
}
}
}
class VC2: UIViewController {
var number = 0
var callback: (() -> Void)?
@IBOutlet weak var numberLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
numberLabel.text = "\(number)"
}
@IBAction func add100Selected(_ sender: UIButton) {
number += 100
numberLabel.text = "\(number)"
}
@IBAction func doneSelected(_ sender: UIButton) {
callback?()
dismiss(animated: true)
}
}
Full Screen Modal Segway个
使用全屏模式段时,您必须使用Done按钮,该按钮将始终保存更改.
Page Sheet Modal Segway (swipeable)个
使用页面工作表模式段,如果您滑动VC2,更改将不会保存.如果无论如何取消VC2,都希望保存更改,则必须在修改数据后立即调用回调函数(在我的示例中,在add100Selected的末尾).
我对每个视频都使用了相同的VC代码(只是在界面生成器中更改了Segue表示).
Interface Builder个
下面是我如何在界面生成器中设置这两个VC的.我在图像中 Select 了分段,因此您可以在属性判断器中看到其设置.