Skip to content

Instantly share code, notes, and snippets.

@yesleon
Created October 7, 2019 10:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yesleon/beaa36b3c45d14906b281fa9cb568f6d to your computer and use it in GitHub Desktop.
Save yesleon/beaa36b3c45d14906b281fa9cb568f6d to your computer and use it in GitHub Desktop.
import UIKit
typealias MutableContext<Value> = (@escaping (inout Value) -> Void) -> Void
class MasterViewController: UITableViewController {
var models = [String]()
// 點選 cell 時會呼叫的工廠方法。
func makeDetailViewController(indexPath: IndexPath) -> DetailViewController? {
let detailVC = DetailViewController()
// handler 將由 detailVC 輸入。
detailVC.modelContext = { [weak self] handler in
guard let self = self else { return }
// 把 self.texts[indexPath.row] 透過 inout 的方式傳給 handler 去存取。
handler(&self.models[indexPath.row])
// handler 處理完 self.texts[indexPath.row] 後,再更新 view。
self.tableView.reloadRows(at: [indexPath], with: .automatic)
}
return detailVC
}
}
class DetailViewController: UIViewController, UITextViewDelegate {
var modelContext: MutableContext<String>!
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// 將讀取 model 的程式碼傳入 modelContext(變成 handler)。
modelContext { self.textView?.text = $0 }
}
func textViewDidChange(_ textView: UITextView) {
// 因為是 inout 所以寫入也沒問題。
modelContext { $0 = textView.text }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment