import UIKit
class ListTableViewController: UITableViewController {
var personList = [person]()
override func viewDidLoad() {
super.viewDidLoad()
loadData{ (list) in
print("完成加载")
//拼接数组
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 = "zhangsang - \(i)";
p.phone = "1860" + String(format:"%06d",arc4random_uniform(100000))
p.title = "boss"
arrayM.append(p)
}
DispatchQueue.main.async(execute: {
//回调异步获取的结果
completion(arrayM)
})
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return personList.count
}
@IBAction func newPerson(_ sender: Any) {
performSegue(withIdentifier: "list2Detail", sender: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination as? DetailViewController
if let indexPath=sender as? IndexPath {
vc?.person = personList[indexpath.row]
vc?.completionCallBack = {
self.tableView.reloadRows(at: [indexpath], with:.automatic)
}
}else{
vc?.completionCallBack = { [weak vc] in
guard let p = vc?.person else {
return
}
self.personList.insert(p, at: 0)
self.tableView.reloadData()
}
}
}
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)
performSegue(withIdentifier: "list2Detail", sender: indexPath)
}
}
import UIKit
class DetailViewController: UITableViewController {
@IBOutlet weak var nameText: UITextField!
@IBOutlet weak var phoneText: UITextField!
@IBOutlet weak var titleText: UITextField!
var person: Person?
var completionCallBack:(()->())?
override func viewDidLoad() {
super.viewDidLoad()
if person != nil {
nameText.text = person?.name
phoneText.text = person?.phone
titleText.text = person?.title
}
}
@IBAction func savePerson(_ sender: Any) {
if person == nil {
person = Person()
}
person?.name = nameText.text
person?.phone = phoneText.text
person?.title = titleText.text
completionCallBack?()
navigationController?.popViewController(animated: true)
}
}
import UIKit
class Person: NSObject {
var name: String?
var phone:String?
var title:String?
}