开发者

Table view Cell Recreation when Cell loaded wih xib

In My TableVIew Im loading开发者_StackOverflow Custome cell With Xib, For Every Entry Of CellForIndexPath,Cell is recreated. how to avoid recreation of cell??

Iam new to IPhone ,Please Help me.


You can use standard methods to cache previously created cells. In your - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath method you should create cells using next approach:

static NSString *CellIdentifier = @"YourCellIdentifier";
cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    // create (alloc + init) new one
    [[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil];        
    cell = myCell;
    self.myCell = nil;
}
// using new cell or previously created

Don't forget that you will store in memory objects for all visible cells. When you will scroll your table this cells will be reused.

For example, if you have 10 visible cells then cell will be == nil for 10 times and you will alloc+init them. When you will scroll down one more cell will be created (as there will be visible 11 cells) and for 12 cell you will reuse cell that was created for first cell.

As @rckoenes said don't forget to set the same CellIdentifier of the cell in IB.

Hope, I was clear.


when you load view from Nib then it will alloc memory every time when cellForRowAtIndexPath called so it is better way to just redraw cell instead of alloc memory every time. May below example will help you.

Parametrically crate label in custom cell. like

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) {
lblusername=[[UILabel alloc]initWithFrame:CGRectMake(70, 10, 150, 25)];
    lblusername.backgroundColor=[UIColor clearColor];
    lblusername.textColor=[UIColor colorWithRed:33.0/255.0 green:82.0/255.0 blue:87.0/255.0 alpha:1.0];
    [contentview addSubview:lblusername];
    [lblusername release];
 }
return self;
}

And call custom cell using below listed code.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{

static NSString *CellIdentifier = @"Cell";

LeaderboardCustomeCell *cell = (LeaderboardCustomeCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[LeaderboardCustomeCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.lblusername.text=@"Hello";
}  
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜