今天來簡要介紹下Apple Watch中的Table組件,以及構建一個簡單的基于Table的Watch App。
簡介
WatchKit,顧名思義,是由蘋果官方提供的用于開發Apple Watch App的框架。在WatchKit中,Table組件對應于iOS中的Table View。但和Table View相比,Table有不少局限,主要體現在以下幾個方面:
- 由于Watch App通過藍牙連接來和匹配的iPhone進行交流,所以對于Table的更新應盡可能減少,以免造成更新不及時的情況。
- Table對應的WKInterfaceTable類沒有使用iOS中UITableView相關的循環機制,所有的Row都會在Table展示前創建好。因此,基于性能考慮,Table的Row數量通常限制在20以內。
- WatchKit中的UI組件必須在Storyboard中進行布局,且沒有AutoLayout功能,因此布局方式十分受限。
- Table中每一種類型的Row都必須有一個對應的Controller來進行管理,Table沒有DataSource和Delegate。
創建 Watch App
打開Xcode,選擇Create a new Xcode project,選擇watchOS -> Application -> iOS App with WatchKit App。我將這個工程取名為WatchTable,且不勾選其它任何選項,進行創建。創建后的工程結構如下圖所示:
可以看到,整個工程分為以下4塊:
- WatchTable文件夾對應于iOS的開發代碼。
- WatchTable WatchKit App文件夾包含watchOS的Storyboard。
- WatchTable WatchKit Extension文件夾包含watchOS的開發代碼。
- Products文件夾包含生成的App。
選擇WatchKit App進行運行,既能夠在Watch Simulator中看到運行結果。
配置 Watch App
Interface.storyboard
打開watchOS的stroyboard,拖入一個Table組件,將其Row數量設為2,在一個Row中拖入一個Label,在另一個Row中拖入一個Image,并在Attributes inspector中進行相應設置,如下圖所示:
Row Controller
在WatchTable WatchKit Extension文件夾下新建兩個文件,用于管理兩種不同類型的Row。選擇File -> New -> File -> watchOS -> Source -> WatchKit Class 進行創建,選擇Subclass of為NSObject,分別命名為LabelRowController和ImageRowController。
對先前在Storyboard中創建的兩個Row的Class分別進行設置。結果如下:
將Label Row中的Outlets進行連接,此時LabelRowController中的代碼如下:
import WatchKit
class LabelRowController: NSObject {
@IBOutlet var label: WKInterfaceLabel!
}
將Image Row中的Outlets進行連接,此時ImageRowController中的代碼如下:
import WatchKit
class ImageRowController: NSObject {
@IBOutlet var image: WKInterfaceImage!
}
InterfaceController
在InterfaceController中執行主要邏輯。首先將Table組件Outlet到InterfaceController中:
@IBOutlet var table: WKInterfaceTable!
awakeWithContext相當于iOS中的ViewDidLoad函數,在這里對Table進行setRowTypes配置。因為WatchKit的Table中,每種類型的Row都有一個Controller進行控制,所以需要在Table顯示前,對所有Row進行配置。各種Row的表示用Identifier來進行區分。
回到Storyboard中,將兩種Row的Identifier分別設置為LabelRow和ImageRow,如下所示:
接著,我打算設置2個LabelRow,1個ImageRow,故在awakeWithContext中添加如下代碼:
let rowArray = ["LabelRow", "LabelRow", "ImageRow"]
self.table.setRowTypes(rowArray)
for i in 0 ..< 2 {
let cell = self.table.rowControllerAtIndex(i) as! LabelRowController
cell.label.setText("label \(i)")
}
let cell = self.table.rowControllerAtIndex(2) as! ImageRowController
cell.image.setImage(UIImage(named: "meow"))
其中,rowArray用于控制Table中各種不同Row的排列順序。通過rowControllerAtIndex可以獲取某個index對應的row,以進行content配置。
運行
至此,一個非常簡單的基于Table的Watch App就構成了。運行后結果如下圖所示:
結語
最終Demo已經上傳到這里,希望這篇文章對你有所幫助_。