この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
WKInterfaceTable を慣れ親しんだ形で
IGInterfaceDataTable は WKInterfaceTable に UITableViewDataSource のような Delegate を追加する、Instagram 社が公開している OSS です。今回はこれを使って WKInterfaceTable を UITableView のように使ってみましょう。
インストール
インストールは CocoaPods で行うか、リポジトリを Clone してプロジェクトファイルごとアプリのプロジェクトに追加するか、いずれかの方法で行いましょう。下記は CocoaPods の Podfile の記述例です。
Podfile
target 'IGInterfaceDataTableSample WatchKit Extension' do
pod 'IGInterfaceDataTable'
end
使ってみる
それでは使ってみましょう。まずは Row の作成が必要です。プロジェクト作成後、Interface.storyboard の Interface Controller に WKInterfaceTable を追加しておきます。そして、Row の Controller (Row の View を管理する Controller) を作成します。
先ほど Storyboard で作成した Row の Controller に、いま作成した RowController クラスを設定します。
また Identifier はあとから Row を参照するために必要なので設定します。
Row を少し作り込みます。Storyboard で Row に Label を追加し、RowController クラスに Outlet を追加します。
次に Label の値をセットするメソッドを実装しましょう。
RowController.h
@import WatchKit;
@interface RowController : NSObject
- (void)setName:(NSString *)name;
@end
#import "RowController.h"
@interface RowController ()
@property (weak, nonatomic) IBOutlet WKInterfaceLabel *nameLabel;
@end
@implementation RowController
- (void)setName:(NSString *)name
{
[self.nameLabel setText:name];
}
@end
ここまでは WKInterfaceTable を普通に実装する流れと同じです。ここからが本題です! InterfaceController に Row を表示する処理を実装していきましょう。IGInterfaceDataTable を使うと、UITableViewDelegate とほぼ同じ感じで実装できます。
#import "InterfaceController.h"
#import "RowController.h"
#import <IGInterfaceDataTable/IGInterfaceDataTable.h>
@interface InterfaceController() <IGInterfaceTableDataSource>
@property (weak, nonatomic) IBOutlet WKInterfaceTable *table;
@property (strong, nonatomic) NSArray *items;
@end
@implementation InterfaceController
- (void)awakeWithContext:(id)context {
[super awakeWithContext:context];
// テーブルのアイテム
self.items = @[@{@"name":@"Cat"},
@{@"name":@"Dog"},
@{@"name":@"Bird"},
@{@"name":@"Rabbit"},
@{@"name":@"Hamster"}];
// Delegateを設定して読み込む
self.table.ig_dataSource = self;
[self.table reloadData];
}
- (void)willActivate {
[super willActivate];
}
- (void)didDeactivate {
[super didDeactivate];
}
// IndexPathに対するRowのIdentifierを指定する
- (NSString *)table:(WKInterfaceTable *)table rowIdentifierAtIndexPath:(NSIndexPath *)indexPath
{
return @"Row";
}
// Sectionに対するRowの数を指定する
- (NSInteger)numberOfRowsInTable:(WKInterfaceTable *)table section:(NSInteger)section
{
return self.items.count;
}
// Rowに対するRowControllerを設定する
- (void)table:(WKInterfaceTable *)table configureRowController:(NSObject *)rowController forIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *object = self.items[indexPath.row];
RowController *controller = (RowController *)rowController;
[controller setName:object[@"name"]];
}
@end
いかがでしょうか。かなり UITableViewDelegate の実装に近いですね!ちなみに Section も利用できるようになっているので、必要であればこちらも使いましょう。
こんな感じで表示されます。
まとめ
WKInterfaceTable の実装はそこまで難しいものではありませんが、IGInterfaceDataTable を使うことで iOS アプリと同様の方法で実装できます。ぜひ使ってみましょう!