
寫過 WatchKit 的人大概都有同感:它的 API 比 UIKit 克制得多。但這份克制其實是好事——我們面對的是一塊戴在手腕上的螢幕,不是口袋裡的手機。控制項幾乎不提供「讀值」的介面,標籤文字之類的內容只能寫入,無法回讀,因此狀態變化的追蹤必須由開發者自己在程式碼裡維護一份。
另一個明顯的差異是:WatchKit 沒有 prepareForSegue,取而代之的是 contextForSegueWithIdentifier。傳給下一個 view controller 的上下文必須是單一 AnyObject 物件——資料和代理物件都得塞進這一個容器裡。作者自己折騰出一個頗為直觀的做法,可以同時把兩者送出去。
WKInterfaceController 拿到自身上下文的方式如下:
class InterfaceController: WKInterfaceController {
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
}
}
storyboard 載入完成後,awakeWithContext 會被呼叫,並把 AnyObject? 交到你手上。理想,但顯然不夠理想:物件得自行轉型,而且因為是 AnyObject 而非 Any,結構體完全不能用,一律得先變成類別實例。
如果只想把一個資料物件當上下文丟給控制器,我們並不希望這個資料物件反過來背著一個 controller 的 delegate 屬性。合理的做法是包一層:做一個同時持有資料與代理的物件,姑且叫它 Context。
最直白的寫法看起來是這樣,但問題也藏在裡面:
class Context {
var object: AnyObject?
var delegate: AnyObject?
}
它看似通用,缺點卻很致命:我們沒辦法像平常那樣把 delegate 轉型成協定(protocol),用 Any 也一樣行不通,想找出通用解法會非常痛苦。與其硬撐,不如把 Context 改成協定,讓具體的上下文型別自己去指定代理與資料的型別。
protocol Context {
typealias DelType
typealias ObjType
var delegate: DelType? { get set }
var object: ObjType? { get set }
}
協定本身不綁定任何型別,這份工作交給符合協定的類別完成:
class BookControllerContext: Context {
typealias DelType = BookControllerDelegate
typealias ObjType = Book
var delegate: DelType?
weak var object: ObjType?
}
於是上下文同時承載了模型與控制器代理,控制器端就能一次取用。
接著看實際傳遞。範例假設外層控制器維護一份書單,內層控制器負責展示某本書的細節。
模型物件:
class Book {
var title: String
var author: String
var description: String
var price: Double
var owned: Bool
init(title: String, author: String, description: String, price: Double, owned: Bool) {
self.title = title
self.author = author
self.description = description
self.price = price
self.owned = owned
}
}
列表列的視圖類別:
class BookRow: NSObject {
@IBOutlet weak var bookTitleLabel: WKInterfaceLabel!
@IBOutlet weak var bookAuthorLabel: WKInterfaceLabel!
@IBOutlet weak var bookPriceLabel: WKInterfaceLabel!
@IBOutlet weak var bookBuyLabel: WKInterfaceLabel!
}
內層控制器用來回報「買了這本書」的代理協定:
protocol BookControllerDelegate {
func didBuyBook(book: Book)
}
書單的外層控制器,關鍵在 contextForSegueWithIdentifier:它在跳轉前建立上下文物件並回傳。
class BookListController: WKInterfaceController, BookControllerDelegate {
@IBOutlet var table: WKInterfaceTable!
var books = [
Book(title: "NSHipster Obscure Topics in Cocoa & Objective-C",
author: "Mattt Thompson",
description: "To be an NSHipster is to care deeply about the craft of writing code.",
price: 25.29, owned: false),
Book(title: "Functional Programming in Swift",
author: "Chris Eidhof, Florian Kugler, Wouter Swierstra",
description: "This book will teach you how to use Swift to apply functional programming techniques to your iOS or OS X projects",
price: 53.07, owned: false)
]
func updateDisplay() {
table.setNumberOfRows(books.count, withRowType: "bookRow")
for i in 0..<books.count {
let row = table.rowControllerAtIndex(i) as! BookRow
row.bookTitleLabel.setText(books[i].title)
row.bookAuthorLabel.setText(books[i].author)
row.bookPriceLabel.setText("Price: \(books[i].price)")
row.bookBuyLabel.setText(books[i].owned ? "Purchased" : "Buy")
}
}
override func contextForSegueWithIdentifier(segueIdentifier: String) -> AnyObject? {
if segueIdentifier == "BookDetail" {
var context = BookControllerContext()
context.object = books[rowIndex]
context.delegate = self
return context
}
return nil
}
override func willActivate() {
super.willActivate()
updateDisplay()
}
// MARK: - BookControllerDelegate
func didBuyBook(book: Book) {
book.owned = true
updateDisplay()
}
}
內層控制器則在 awakeWithContext 中把上下文拆開,取出模型與代理:
class BookController: WKInterfaceController {
var delegate: BookControllerDelegate?
var book: Book!
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
let ctx = context as! BookControllerContext
book = ctx.object
delegate = ctx.delegate
}
@IBOutlet weak var buyBtn: WKInterfaceButton!
@IBAction func buyPressed() {
delegate?.didBuyBook(book)
popController()
}
}
import WatchKit
/* Model */
protocol Context {
typealias DelType
typealias ObjType
var delegate: DelType? { get set }
var object: ObjType? { get set }
}
class BookControllerContext: Context {
typealias DelType = BookControllerDelegate
typealias ObjType = Book
var delegate: DelType?
weak var object: ObjType?
}
class Book {
var title: String
var author: String
var description: String
var price: Double
var owned: Bool
init(title: String, author: String, description: String, price: Double, owned: Bool) {
self.title = title
self.author = author
self.description = description
self.price = price
self.owned = owned
}
}
/* View */
class BookRow: NSObject {
@IBOutlet weak var bookTitleLabel: WKInterfaceLabel!
@IBOutlet weak var bookAuthorLabel: WKInterfaceLabel!
@IBOutlet weak var bookPriceLabel: WKInterfaceLabel!
@IBOutlet weak var bookBuyLabel: WKInterfaceLabel!
}
/* Controller */
protocol BookControllerDelegate {
func didBuyBook(book: Book)
}
class BookController: WKInterfaceController {
var delegate: BookControllerDelegate?
var book: Book!
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
let ctx = context as! BookControllerContext
book = ctx.object
delegate = ctx.delegate
}
@IBOutlet weak var buyBtn: WKInterfaceButton!
@IBAction func buyPressed() {
delegate?.didBuyBook(book)
popController()
}
}
class BookListController: WKInterfaceController, BookControllerDelegate {
@IBOutlet var table: WKInterfaceTable!
var books = [
Book(title: "NSHipster Obscure Topics in Cocoa & Objective-C",
author: "Mattt Thompson",
description: "To be an NSHipster is to care deeply about the craft of writing code.",
price: 25.29, owned: false),
Book(title: "Functional Programming in Swift",
author: "Chris Eidhof, Florian Kugler, Wouter Swierstra",
description: "This book will teach you how to use Swift to apply functional programming techniques to your iOS or OS X projects",
price: 53.07, owned: false)
]
func updateDisplay() {
table.setNumberOfRows(books.count, withRowType: "bookRow")
for i in 0..<books.count {
let row = table.rowControllerAtIndex(i) as! BookRow
row.bookTitleLabel.setText(books[i].title)
row.bookAuthorLabel.setText(books[i].author)
row.bookPriceLabel.setText("Price: \(books[i].price)")
row.bookBuyLabel.setText(books[i].owned ? "Purchased" : "Buy")
}
}
override func contextForSegueWithIdentifier(segueIdentifier: String) -> AnyObject? {
if segueIdentifier == "BookDetail" {
var context = BookControllerContext()
context.object = books[rowIndex]
context.delegate = self
return context
}
return nil
}
override func willActivate() {
super.willActivate()
updateDisplay()
}
// MARK: - BookControllerDelegate
func didBuyBook(book: Book) {
book.owned = true
updateDisplay()
}
}
這就是 WatchKit 裡同時傳遞資料與代理的完整思路。要接新的情境,只要照著 Context 協定再寫一個符合型別即可:例如作者頁面的 AuthorControllerContext,裡頭放 Author 資料與 AuthorControllerDelegate。
這是作者目前找到、用來繞開 WatchKit 種種限制的最佳解法,但肯定不是唯一解。如果你有更好的主意,歡迎聯絡原作者 Korey Hinton。
譯自:https://koreyhinton.com/blog/watchkit-delegates-and-contexts.html