例:自定義單元格中有一個button和一個TextView
1.在XCode中選擇新建->Cocoa Touch->Objective-C Class->名字:MyCell 繼承:UITableViewCell
2.
MyCell.h文件:
@interface MyCell : UITableViewCell { UITextView *myTextView; } - (IBAction)btnAction:(id)sender; @property (retain, nonatomic) IBOutletUITextView *myTextView; @end
MyCell.m文件:
#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為MyCell
(2)設定其重用標識符(Identifier),此處設置為:CellReuseID,設定重用標識符可以減少內存的分配,合理利用內存。
5.將MyCell.xib中的控件連接到MyCell.h中
8.最后在UITabelView的委托方法中加載此定制的Cell,代碼如下:
- (UITableViewCell *)tableView:(UITableView *)tableView //nib設置了重用標識符,則tableview會使用重用機制 cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellid=@"CellReuseID"; MyCell *cell = (MyCell *)[tableView dequeueReusableCellWithIdentifier:cellid];(尋找標識符為cellid並且沒被用到的cell用於重用)
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;
}