2013年5月1日 星期三

TableViewCell ( with Custom ViewCell ) with Stroyboard



第一步
開啟 Storyboard
把 Cell 顯示的元件 透過 Storyboard 都給 拉一拉 , 把 outlet 擺設做好

第二步
新增一個 Class ,


在此我取這個 Class 的名稱為 ByTimeViewCell , 要選 繼承自(Subclass of) UITableViewCell


好了 , 上面兩個圖之後 , 就會產生出  Class ( 有 .h 也有 .m )






第三步 ,
於 ByTimeViewCell.h / .m 添加  outlet 物件的 @property / @synthesize

//  ByTimeViewCell.h
@property (nonatomic, weak) IBOutlet UILabel *firstLabel;
@property (nonatomic, weak) IBOutlet UILabel *secondLabel;
@property (nonatomic, weak) IBOutlet UILabel *thirdLabel;

//  ByTimeViewCell.m
@synthesize firstLabel;
@synthesize secondLabel;
@synthesize thirdLabel;




第四步
去到 Storyboard , 指派 ByTimeViewCell Class 給 Cell 物件
如果 這個 Custom Class 下拉選單 , 沒有出現 剛剛新增的 .h .m Class ,
請看一下 .h .m Class 應該是還沒儲存

如下圖 尚未儲存




如下圖 ( 當下檔案 Command+S 儲存快速鍵 )已經儲存


如果 .h .m 已經儲存 , 但 Class 還是沒有顯示 ,
可嘗試 關閉其他的 xcode Project 專案 , 只剩下 待解決的這個 Project ,
然後整個 xcode 關掉 重開 , Project 重開

再不行 , 還有一招 , 等下再講



第五步
去到 Storyboard 把 outlet 指派 Object
滑鼠指標移到最右邊的 圈圈 , 圈圈 裡頭會多個 + 號 , 然後按著
拉到 預覽可視版型的 物件上頭 再將滑鼠左鍵放開





第六步
去到 TableViewController.m
編輯 引用 .h
 #import "ByTimeViewCell.h"



第七步
去到
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
客制 ViewCell


當上方的框框改寫成如下
ByTimeViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

下方的框框
就可以以 . 帶出我們剛剛所新增的 三個 Label 物件
    cell.firstLabel.text = (NSString*)[dictionary objectForKey:@"StayTime"];
    cell.secondLabel.text = [NSString stringWithFormat:@"%02i:%02i", components.hour, components.minute];
    cell.thirdLabel.text = strDist;


這個 Function 第一行 CellIdentifier , ByTimeTableCell 自己命名
static NSString *CellIdentifier = @"ByTimeTableCell";
但需要與 Storyboard 裡頭 相同

如果不相同 , 編譯不會有 Warring , 也不會有 Error ,
情況會是 滑動 Cell 時 , 都是重新再畫 Cell , 比較耗用效能 , 因為沒有重複使用

如果 Storyboard 空白 , 編譯時會有 Warring , 也不會有 Error
但 , 執行起來 , Cell 會空空的 , 帶不出資料





 好了 , 這樣就把 Custom ViewCell 講完了


[EOF]










沒有留言:

張貼留言