UITableView Cell восстанавливается - PullRequest
1 голос
/ 12 августа 2011

У меня UITableViewCell с UILabel и UISwitch. По умолчанию все UISwitch выключено.

Как только я включу коммутатор, а затем прокручиваю таблицу, значение коммутатора снова устанавливается в значение по умолчанию, т.е. отключено

Ниже приведен код, который я использовал:

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

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell != nil) cell = nil;
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    if (indexPath.row == 0) {
        UILabel *lbl1 = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 100, 30)];
        lbl1.text = @"Some Text";
        [cell addSubview:lbl1];

        switch = [[UISwitch alloc] initWithFrame:CGRectMake(190, 10, 200, 30)];
        [switch setOn:NO];
        switch.tag = 1;
        [switch addTarget:self action:@selector(switchTapped:) forControlEvents:UIControlEventChanged];
        [cell addSubview:switch];
    }

}

// Ниже мой метод switchTapped:

- (void) switchTapped: (id)sender {
    UISwitch *tapSwitch = (UISwitch *)sender;

    switch (tapSwitch.tag) {
        case 1:
            if (tapSwitch.on) {
              // do something
            }
            else {
                // do something
            }
            break;
        case 2:
            if (tapSwitch.on) {
                // do something
            }
            else {
                // do something
            }
            break;
}

Я что-то здесь не так делаю?

Спасибо.

Ответы [ 2 ]

1 голос
/ 12 августа 2011

Вы используете действительно неприятный код, который восстанавливает ячейку каждый раз, когда она необходима:

if(cell != nil) 
{
   cell = nil; 
}

if (cell == nil) 
{ 
...
}

Связываете ли вы состояние вашего переключателя с каким-либо удержанным объектом (например, объект модели предмета, где отдельная ячейка отражает предмет)?

0 голосов
/ 12 августа 2011

Вот как я пишу свой код рисования ячейки:

По сути, внутри моего if (cell == nil) {...} я делаю все "initWithFrame".Что-нибудь вне этого, я просто устанавливаю значение, такое как текст метки.Не используйте initWithFrame вне блока кода if (cell == nil) {...}.

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reusableCell];

    if(cell == nil)
    {        
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reusableCell] autorelease];

        thumbnail = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 106, 81)];

        feedTitle = [[UILabel alloc] initWithFrame:CGRectMake(116, 3, [IOSDevice screenWidth] - 140, 25)];
        postDate = [[UILabel alloc] initWithFrame:CGRectMake(116, 10, [IOSDevice screenWidth] - 140, 50)];
        description = [[UILabel alloc] initWithFrame:CGRectMake(116, 45, [IOSDevice screenWidth] - 140, 50)];

        // setting tag reminders so we can identify the element to replace
        [thumbnail setTag:1];
        [feedTitle setTag:2];
        [postDate setTag:3];
        [description setTag:4];

        [[cell contentView] addSubview:thumbnail];
        [[cell contentView] addSubview:feedTitle];
        [[cell contentView] addSubview:description];
        [[cell contentView] addSubview:postDate];

        [thumbnail release];
        [feedTitle release];
        [description release];
        [postDate release];
    }

    thumbnail = (UIImageView *)[[cell contentView] viewWithTag:1];
    feedTitle = (UILabel *)[[cell contentView] viewWithTag:2];
    postDate = (UILabel *)[[cell contentView] viewWithTag:3];
    description = (UILabel *)[[cell contentView] viewWithTag:4];

    [feedTitle setBackgroundColor:[UIColor clearColor]];
    [feedTitle setFont:[UIFont fontWithName:@"Helvetica-Bold" size:16]];
    [feedTitle setTextColor:[UIColor colorWithRed:0.215 green:0.215 blue:0.215 alpha:1.0]];

    [description setBackgroundColor:[UIColor clearColor]];
    [description setFont:[UIFont fontWithName:@"Helvetica" size:12]];
    [description setTextColor:[UIColor colorWithRed:0.328 green:0.328 blue:0.328 alpha:1.0]];
    [description setNumberOfLines:2];
    [description setLineBreakMode:UILineBreakModeWordWrap];

    [postDate setBackgroundColor:[UIColor clearColor]];
    [postDate setFont:[UIFont fontWithName:@"Helvetica" size:12]];
    [postDate setTextColor:[UIColor colorWithRed:0.707 green:0.180 blue:0.141 alpha:1.0]];

    [thumbnail setImage:[[items objectAtIndex:[indexPath row]] objectForKey:@"thumb"]];

    [feedTitle setText:[[items objectAtIndex:[indexPath row]] objectForKey:@"title"]];
    [description setText:[[items objectAtIndex:[indexPath row]] objectForKey:@"summary"]];

    // Format date
    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];  
    [dateFormatter setDateStyle:NSDateFormatterLongStyle];
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];

    [postDate setText:[dateFormatter stringFromDate:[[items objectAtIndex:[indexPath row]] objectForKey:@"date"]]];

    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];

    if([feedList contentOffset].y < -50)
    {
        shouldUpdate = TRUE;

        [activityIndicator stopAnimating];

        [feedList setContentOffset:CGPointMake(0, -30) animated:NO];
        [self loadData];

        loadingLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, -25, [IOSDevice screenWidth], 20)];
        [loadingLabel setText:@"Loading New Data"];
        [loadingLabel setTextAlignment:UITextAlignmentCenter];
        [loadingLabel setBackgroundColor:[UIColor clearColor]];
        [loadingLabel setTextColor:[UIColor colorWithRed:0.215 green:0.215 blue:0.215 alpha:1.0]];
        [loadingLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:14]];

        reloadingSpinner = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(70, -25, 20, 20)];
        [reloadingSpinner setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
        [reloadingSpinner startAnimating];
        [reloadingSpinner setHidesWhenStopped:YES];

        [feedList addSubview:reloadingSpinner];
        [feedList addSubview:loadingLabel];
    }

    return cell;
}
...