Программно изменить состояние UISwitch с помощью анимации

У меня есть UITableView с некоторыми ячейками, содержащими UISwitches:

UISwitch* actSwitch = (UISwitch*)[cell viewWithTag: SWITCH_TAG];
[actSwitch addTarget: self
              action: @selector(actSwitchChanged:) 
    forControlEvents: UIControlEventValueChanged];
BOOL value = [appSettings.lock_when_inactive boolValue];
[actSwitch setOn: value animated:NO];

И я также хочу перезаписать метод didSelectRowAtIndexPath: для переключения соответствующих UISwitch:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    NSString *cellType = [self typeOfCellForIndexPath:indexPath];
    if ( cellType  == @"CellWithSwitch" )
    {
        UISwitch* actSwitch = (UISwitch*)[[[self tableView] cellForRowAtIndexPath:indexPath ] viewWithTag: SWITCH_TAG];
        BOOL value = [actSwitch isOn];
        [actSwitch setOn:!value animated:YES]; // <-- HERE IS THE PROBLEM
        [self actSwitchChanged: actSwitch];
    }
    else if ( cellType == @"CellWithoutSwitch" )
    {
        // other actions
    }
}

В обеих ситуациях, либо я нажимаю на UISwitch напрямую, либо щелкаю по ячейке, он меняет его состояние и правильно вызывает actSwitchChanged: .

Но в случае, если я нажму на ячейку , мой UISwitch не анимирует переключение из одного состояния в другое, он просто меняет свое состояние за один момент.

Итак [actSwitch setOn:! value animated: YES] недостаточно сказать, чтобы выполнить анимацию?


Вот как я устанавливаю и вызываю конфигурационную ячейку:

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

    UITableViewCell *cell = nil;
    NSString *EnabledCellIdentifier = [self typeOfCellForIndexPath:indexPath];  
    cell = [tableView dequeueReusableCellWithIdentifier:EnabledCellIdentifier];

    if (cell == nil) 
    {
        cell = [self cellForType:EnabledCellIdentifier];
    }
    [self cofigureCell:cell forIndexPath:indexPath];

    return cell;
}

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

- (void)cofigureCell:(UITableViewCell*)cell forIndexPath:(NSIndexPath*)indexPath {
    switch ( indexPath.section )
    {
        case 0: 
            // not this
        case 1: 
        {
            switch ( indexPath.row )
            {
                case 0:
                {
                    cell.textLabel.text = @"Limit passwords attempts";
                    UISwitch* actSwitch = (UISwitch*)[cell viewWithTag: SWITCH_TAG];
                    [actSwitch addTarget: self
                                  action: @selector(actSwitchChanged:) 
                        forControlEvents: UIControlEventValueChanged];
                    BOOL value = [appSettings.limit_password_attempts boolValue];
                    [actSwitch setOn: value animated:NO];

                    break;
                }
                //other rows of this section here are being configured
            }
            break;
        }

        case 2: 
        {
            switch ( indexPath.row )
            {
                case 0:
                {
                    cell.textLabel.text = @"Lock when inactive";
                    UISwitch* actSwitch = (UISwitch*)[cell viewWithTag: SWITCH_TAG];
                    [actSwitch addTarget: self
                                  action: @selector(actSwitchChanged:) 
                        forControlEvents: UIControlEventValueChanged];
                    BOOL value = [appSettings.lock_when_inactive boolValue];
                    [actSwitch setOn: value animated:NO];

                    break;
                }
                //other rows of this section here are being configured
            }
            break;
        }
        default:

            break;
    }
}

Но когда я отлаживаю шаг за шагом и прохожу этот шаг:

[actSwitch setOn:! Анимированное значение: ДА]; // <- ВОТ ПРОБЛЕМА

actSwitch меняет свое состояние только после [self actSwitchChanged: actSwitch]; измененной модели данных и вызовов [self.tableView reloadData];

Может быть причина в том, что у меня две ячейки с UISwitches, и между ними есть конфликт? Может быть, есть лучший способ получить UISwitch из ячейки, чем этот мой код?:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    NSString *cellType = [self typeOfCellForIndexPath:indexPath];
    if ( cellType  == @"CellWithSwitch" )
    {
        UISwitch* actSwitch = (UISwitch*)[[[self tableView] cellForRowAtIndexPath:indexPath ] viewWithTag: SWITCH_TAG];
        BOOL value = [actSwitch isOn];
        [actSwitch setOn:!value animated:YES]; // <-- HERE IS THE PROBLEM
        [self actSwitchChanged: actSwitch];
    }
    else if ( cellType == @"CellWithoutSwitch" )
    {
        // other actions
    }
}
5
задан Cœur 30 November 2017 в 06:17
поделиться