您好,登錄后才能下訂單哦!
自定義單元格
當(dāng)蘋果公司提供給的單元格樣式不能我們的業(yè)務(wù)需求的時(shí)候,我們需要自定義單元格。在iOS 5之前,自定義單元格可以有兩種實(shí)現(xiàn)方式:代碼實(shí)現(xiàn)和用xib技術(shù)實(shí)現(xiàn)。用xib技術(shù)實(shí)現(xiàn)相對比較簡單,創(chuàng)建一個xib文件,然后定義一個繼承 UITableViewCell類單元格類即可。在iOS 5之后我們又有了新的選擇,故事板實(shí)現(xiàn)方式,這種方式比xib方式更簡單一些。
我們把簡單表視圖案例的原型圖修改一下,這種情況下四種內(nèi)置的單元格樣式就不合適了。
采用“Single View Application”工程模版創(chuàng)建一個名為“CustomCell”的工程,Table View屬性的“Prototype Cells”項(xiàng)目設(shè)為1(除此之外其它的操作過程與上同)。
設(shè)計(jì)畫面中上部會有一個單元格設(shè)計(jì)畫面,我們可以在這個位置進(jìn)行單元格布局的設(shè)計(jì)。從對象庫拖拽一個Label和Image View到單元格設(shè)計(jì)畫面,調(diào)整好它們的位置。
創(chuàng)建自定義單元格類CustomCell, 選擇UITableViewCell為父類
再 回到IB設(shè)計(jì)畫面,在IB中左邊選擇“Table View Controller Scene” → “Table View Controller” → “Table View” → “Table View Cell”,打開單元格的標(biāo)識檢查器,在Class的選項(xiàng)中選擇CustomCell類。
為Lable和ImageView控件連接輸出口
本案例的代碼如下:
- //
- // CustomCell.h
- // CustomCell
- #import <UIKit/UIKit.h>
- @interface CustomCell : UITableViewCell
- @property (weak, nonatomic) IBOutlet UILabel *name;
- @property (weak, nonatomic) IBOutlet UIImageView *p_w_picpath;
- @end
- //
- // CustomCell.m
- // CustomCell
- #import “CustomCell.h”
- @implementation CustomCell
- @end
CustomCell類的代碼比較簡單,在有些業(yè)務(wù)中還需要定義動作。
修改視圖控制器ViewController.m中的tableView: cellForRowAtIndexPath:方法,代碼如下:
- - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
- {
- static NSString *CellIdentifier = @”Cell”;
- CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
- if (cell == nil) {
- cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
- }
- NSUInteger row = [indexPath row];
- NSDictionary *rowDict = [self.listTeams objectAtIndex:row];
- cell.name.text = [rowDict objectForKey:@"name"];
- cell.p_w_picpath.p_w_picpath = [UIImage p_w_picpathNamed:[rowDict objectForKey:@"p_w_picpath"]];
- NSUInteger row = [indexPath row];
- NSDictionary *rowDict = [self.listFilterTeams objectAtIndex:row];
- cell.textLabel.text = [rowDict objectForKey:@"name"];
- NSString *p_w_picpathPath = [rowDict objectForKey:@"p_w_picpath"];
- p_w_picpathPath = [p_w_picpathPath stringByAppendingString:@".png"];
- cell.p_w_picpath.p_w_picpath = [UIImage p_w_picpathNamed:p_w_picpathPath];
- cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
- return cell;
- }
我們看到if (cell == nil){}代碼被移除,這是因?yàn)槲覀冊贗B中已經(jīng)將重用標(biāo)識設(shè)定為Cell了。 方法中的其它代碼與簡單表一致,此處不再贅述。運(yùn)行一下。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。