开发者

Cocoa - UITableViewController strange behaviour !

开发者 https://www.devze.com 2023-02-24 08:26 出处:网络
I\'m losing my mind on this: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

I'm losing my mind on this:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *MyIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; 

    UILabel *label;

    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
        label=[[UILabel alloc]initWithFrame:CGRectMake(20, 20, 200, 30)];
        [cell addSubview:label];
        开发者_运维问答[label setText:[NSString stringWithFormat: @"%d",indexPath.row]];
    }

    return cell;
}

in the cells' labels, i see this numbers instead of the progression I am expecting (0,1,2,3,4...):

0 1 2 0 4 1 2 0 4 1

any idea where's the error? Seems I can't figure this out.

EDIT resolved after putting the initialization of the label after the cell==nil{} block.(don't know why i put that there in the first place.)


You need to perform cell configuration outside of the if:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; 
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(20, 20, 200, 30)];
    [cell addSubview:label];
    [label release];
}   

[label setText:[NSString stringWithFormat: @"%d",indexPath.row]];

Oh - and you should release the label after adding it to avoid a memory leak :)


Try this

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

{

static NSString *MyIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];

UILabel *label;

if (cell == nil)

{

   cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];

}

label=[[UILabel alloc]initWithFrame:CGRectMake(20, 20, 200, 30)];

[cell addSubview:label];

[label setText:[NSString stringWithFormat: @"%d",indexPath.row]];

[label release];

return cell;

0

精彩评论

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