自定义UITabelViewCell

来源:互联网 发布:psd传感器 单片机 编辑:程序博客网 时间:2024/06/07 23:48

自定义UITableViewCell详细步骤

例:自定义单元格中有一个button和一个TextView

1.在XCode中选择新建->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为MyCell

    (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) <br>  { <br>    cell = [[[NSBundle mainBundle] loadNibNamed:@"MyCell" owner:self options:nil] lastObjects]; <br>//如果此nib没有设置标识符,则当其移出屏幕时会自动释放(dealloc),可以用cell = [MyCell alloc] init];使其不自动释放<br>  }<br>   NSUInteger row = [indexPath row]; <br>  [cell.myTextView setText:@"123456"]; <br>  cell.myTextView.editable = NO; <br>  return cell;<br> }