WatchKit 的 WKInterfaceTable 簡單使用

轉自:http://nonomori.farbox.com/post/watchkit-de-wkinterfacetable-jian-dan-shi-yong

WKInterfaceTable 類似 UITableView, 其用途即展示一個表格並且用戶可以與之交互。但不同的是 WKInterfaceTable 的功能更加簡單,使用上也很粗暴直接。

本文一步步演示了創建一個簡單的包含 WKInterfaceTable 的 Apple Watch App!

我們首先按照老辦法,創建一個 Single View Application 模板的 iOS 應用。
工程創建好後,點擊 File -> Add -> Target,選擇 Apple Watch 標籤下的 Watch App。Xcode 會添加一個工程名 Watch App 目錄。同時,運行 Watch App 的 scheme 也會被添加。


選中 Watch App 的 scheme,編譯運行。模擬器並不會同時啓用 Apple Watch 模擬器,需要點擊 Hardware -> External Displays -> Apple Watch。


Watch App 成功運行。

接下來就是添加 WKInterfaceTable。

點擊 Watch App 目錄下的 storyboard,拖拽一個 WKInterfaceTable 到界面上。然後拖一個 table 的 outlet 到 InterfaceController 上,我們命名爲 tableView。


不同於 UITableView 每一個 Cell 的原型對應一個 UITableViewCell,WKInterfaceTable 是使用 TableRowController 作爲原型,其就是 NSObject。

我們在 Watch Extension 目錄添加一個繼承自 NSObject 的類,取名 RowType,將 storyboard 中的 RowController 的類改爲剛創建的 RowType,並且賦一個 identifier:rowType。

拖拽一個 WKInterfaceLabel 到 row 上,同樣拖一個 outlet 到 RowType。注意,要在 RowType 上添加 WatchKit 模塊:

import UIKit
import WatchKit

class RowType: NSObject {
    @IBOutlet weak var labelNumber: WKInterfaceLabel!
}

接下來就是告訴 table 有多少數據,該如何展示了。我們直接在 willActivate 方法中對 table 進行初始化。

不同於 UITableView 還需要寫 DataSource 方法回調,WKInterfaceTable 非常簡單,直接使用setNumberOfRows:withRowType 方法定義行數與 row 原型。這裏 RowType 就是 RowController 的 identifier。對每個 row 進行配置也是通過 rowControllerAtIndex 方法遍歷得到每一個 rowController,依次配置。

override func willActivate() {
    super.willActivate()
    //設置行數與原型類型
    self.tableView.setNumberOfRows(10, withRowType: "rowType") 
    //遍歷,獲取每一個 rowController,配置
    for i in 0..<self.tableView.numberOfRows {
        let row: RowType = self.tableView.rowControllerAtIndex(i) as RowType
        row.labelNumber.setText("\(i)")
    }   
}

運行,得如下結果:

接下來是定義交互,我們需要點擊某一行的回調,這裏很像 UITableView 的 didSelectRowAtIndex, 我們直接在 InterfaceController 中添加 table:didSelectRowAtIndex 方法。

override func table(table: WKInterfaceTable, didSelectRowAtIndex rowIndex: Int) {
    NSLog("\(rowIndex)")
}

運行:
image

至此,一個簡單的包含 WKInterfaceTable 的 Watch App 就完成了。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章