自定义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; 
}

posted on 2014-06-27 16:32  金玉游龙  阅读(293)  评论(0编辑  收藏  举报

导航