下面简单的进行正向传值的实例
界面使用storyboard进行搭建
创建联系人数组
var personList = [Person]()
override func viewDidLoad() {
super.viewDidLoad()
调用闭包加载的闭包
loadData { (list) in
print(list)
拼接数组 闭包中定义好的代码在需要的时候用Self
self.personList += list
加载完毕数据,刷新数据源
self.tableView.reloadData()
}
}
模拟异步加载 利用闭包回调
private func loadData(completion:@escaping (_ list: [Person]) -> ())->(){
创建线程
DispatchQueue.global().async {
print("正在努力加载....")
休眠一秒钟
Thread.sleep(forTimeInterval: 1)
var arrayM = [Person]()
for i in 0..<20{
let p = Person()
p.name = "zhang - \(i)"
p.phone = "13733225544"
p.title = "boss"
arrayM.append(p)
}
回到主线程
DispatchQueue.main.async {
执行,回调
completion(arrayM)
}
}
}
MARK: - 控制器跳转的方法
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let VC = segue.destination as! DetailTableViewController
//确定选中的indexPath
if let IndexPath = sender as? IndexPath{
进行数据的传递
VC.person = personList[IndexPath.row]
}
}
MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return personList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellID", for: indexPath)
cell.textLabel?.text = personList[indexPath.row].name
cell.detailTextLabel?.text = personList[indexPath.row].phone
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
//执行segue
performSegue(withIdentifier: "list2detail", sender: indexPath)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
联系人详细界面
DetailTableViewController: UITableViewController {
@IBOutlet var titleTextField: UITextField!
@IBOutlet var nameTextField: UITextField!
@IBOutlet var phoneTextField: UITextField!
定义person 的对象
var person : Person?
override func viewDidLoad() {
super.viewDidLoad()
进行赋值
titleTextField.text = person?.title
nameTextField.text = person?.name
phoneTextField.text = person?.phone
}
//点击item保存按钮的方法
@IBAction func savePreson(_ sender: Any) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
完成实例图
跳转到明细的界面