下面簡(jiǎn)單的進(jìn)行正向傳值的實(shí)例
界面使用storyboard進(jìn)行搭建
創(chuàng)建聯(lián)系人數(shù)組
var personList = [Person]()
override func viewDidLoad() {
super.viewDidLoad()
調(diào)用閉包加載的閉包
loadData { (list) in
print(list)
拼接數(shù)組 閉包中定義好的代碼在需要的時(shí)候用Self
self.personList += list
加載完畢數(shù)據(jù),刷新數(shù)據(jù)源
self.tableView.reloadData()
}
}
模擬異步加載 利用閉包回調(diào)
private func loadData(completion:@escaping (_ list: [Person]) -> ())->(){
創(chuàng)建線程
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 {
執(zhí)行,回調(diào)?
completion(arrayM)
}
}
}
MARK: - 控制器跳轉(zhuǎn)的方法
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let VC = segue.destination as! DetailTableViewController
//確定選中的indexPath
if let IndexPath = sender as? IndexPath{
進(jìn)行數(shù)據(jù)的傳遞
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)
//執(zhí)行segue
performSegue(withIdentifier: "list2detail", sender: indexPath)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
聯(lián)系人詳細(xì)界面
?DetailTableViewController: UITableViewController {
@IBOutlet var titleTextField: UITextField!
@IBOutlet var nameTextField: UITextField!
@IBOutlet var phoneTextField: UITextField!
定義person 的對(duì)象
var person : Person?
override func viewDidLoad() {
super.viewDidLoad()
進(jìn)行賦值
titleTextField.text = person?.title
nameTextField.text = person?.name
phoneTextField.text = person?.phone
}
//點(diǎn)擊item保存按鈕的方法
@IBAction func savePreson(_ sender: Any) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
完成實(shí)例圖
跳轉(zhuǎn)到明細(xì)的界面