自定义cell 用xib

例:自定义单元格中有一个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; 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值