通常大家都不太想用最簡單的預設表單,因為我們想塞進去的資料和介面千變萬化,於是有必要客製化TableViewCell,並且讓它可以重複使用!
TableViewCell的使用頻率相當高,無論是哪一領域的應用或遊戲,無不會以列表式的介面來呈現資料,學起來之後再把十分吸引人的美術圖貼上去,APP成品會讓人愛不釋手呢!
在專案中新增檔案,有兩個步驟:
- iOS中Cocoa Touch的Objective-C class
- iOS中User Interface的Empty
兩者命同樣的名稱,結束後產生.h、.m、.xib三個檔案。
.xib:
在IB中,拉個TableViewCell出來,把想要的UI元件放進去這個Cell。
.h:
根據.xib放到TableViewCell中的UI元件,分別宣告相對應形態的IBOutlet Property,並拉藍線建立戀節關係。最後宣告回傳cell的method。無法成功拉藍線是因為要在Custom Class設定PLProductCell,讓IB可找到Class宣告的Property。
@interface PLProductCell : UITableViewCell @property (nonatomic, retain) IBOutlet UIImageView *productImage; @property (nonatomic, retain) IBOutlet UITextView *introductTextView; @property (nonatomic, retain) IBOutlet UIButton *detailButton; + (PLProductCell *)cell; @end
.m:
實作回傳cell的method。
+ (PLProductCell *)cell
{
NSArray *items = [[NSBundle mainBundle] loadNibNamed:@"PLProductCell" owner:nil options:nil];
return items.lastObject;
}
之後在想要塞入此TableViewCell的ViewController引入該.h檔,將TableView拉藍線建立File’s Owner的Outlets(DataSource和Delegate)。接著實作一定要的以下兩個method。
#pragma mark - TableView Delegate Methods
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 7;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView setSeparatorColor:[UIColor clearColor]];
PLProductCell *cell = [PLProductCell cell];
cell.introductTextView.text = [NSString stringWithFormat:@"Number: %i", indexPath.row + 1];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
return cell;
}
cell中擁有的Property都可以叫出來修改~
如此就能編譯執行出結果囉~
參考:老闆的夥伴。



Comments on: "[iOS] 客製化TableViewCell (Custom TableViewCell)" (2)
[…] [iOS] 客製化TableViewCell (Custom TableViewCell) https://cg2010studio.com/2013/05/09/ios-%E5%AE%A2%E8%A3%BD%E5%8C%96tableviewcell-custom-tableviewcel… […]
讚讚
[…] 雖然可以客製化TableViewCell (Customize TableViewCell)來完成,但是客製化CollectionViewCell (Customize CollectionViewCell)能讓我們更簡單地實作,而且landscape和portrait這兩種界面的轉換它都幫我們處理好,接著只要撰寫幾行程式碼,就可以做出像內建相簿那樣的格子瀑布流喔! […]
讚讚