例:自定義單元格中有一個button和一個TextView
1.在XCode中選擇新建(command+n)->Cocoa Touch->Objective-C Class->名字:MyCell 繼承:UITableViewCell
2.
MyCell.h文件:
1
2
3
4
5
6
7
|
@interface MyCell
: UITableViewCell { UITextView
*myTextView; } -
( IBAction )btnAction:( id )sender; @property (retain,
nonatomic )
IBOutletUITextView *myTextView; @end |
MyCell.m文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
#import
"MyCell.h" @implementation MyCell @synthesize myTextView; -
( id )initWithStyle:(UITableViewCellStyle)style
reuseIdentifier:( NSString *)reuseIdentifier { self =
[ super initWithStyle:style
reuseIdentifier:reuseIdentifier]; if ( self )
{ } return self ; } -
( void )setSelected:( BOOL )selected
animated:( BOOL )animated {
[ super setSelected:selected
animated:animated];} -
( IBAction )btnAction:( id )sender
{} |
3.在XCode中選擇新建->User Interface->Empty XIB->名字:MyCell
4.打開空的MyCell.xib文件,將UITableViewCell拖到MyCell.xib窗口中,並在屬性檢查器上
(1)修改Custom Class爲MyCustomerCell
(2)設定其重用標識符(Identifier),此處設置爲:CellReuseID,設定重用標識符可以減少內存的分配,合理利用內存。
5.將MyCell.xib中的控件連接到MyCell.h中
8.最後在UITabelView的委託方法中加載此定製的Cell,代碼如下:
1
2
3
4
5
|
-
(UITableViewCell *)tableView:(UITableView *)tableView //nib設置了重用標識符,則tableview會使用重用機制 cellForRowAtIndexPath:( NSIndexPath *)indexPath { static NSString *cellid=@ "CellReuseID" ; MyCell
*cell = (MyCell *)[tableView dequeueReusableCellWithIdentifier:cellid];(尋找標識符爲cellid並且沒被用到的cell用於重用) |
1
|
if (cell== nil ) { cell
= [[[ NSBundle mainBundle]
loadNibNamed:@ "MyCell" owner: self options: nil ]
lastObjects]; //如果此nib沒有設置標識符,則當其移出屏幕時會自動釋放(dealloc),可以用cell
= [MyCell alloc] init];使其不自動釋放 } NSUInteger
row = [indexPath row]; [cell.myTextView
setText:@"123456"]; cell.myTextView.editable
= NO; return
cell; }
|